javascript - Color picker set individual attribute in JQuery each -
i have 3 buttons on page i've set array. i'm using $.each iterate through them , inside color picker function. i'm trying have (last) clicked button change background color, right now, if click 3 before using color picker, change color. need button last clicked change color. jsfiddle
var test1 = $('#test1'); var test2 = $('#test2'); var test3 = $('#test3'); var elements = [test1, test2, test3] $.each(elements, function(i) { function handler() { $('#color').change(function(){ $(elements[i]).unbind('click', handler); elements[i].css('background-color', this.value); }); } $(elements[i]).bind('click', handler) });
your solution seems overly complex. simpler solution might this:
- add click handlers buttons. when button clicked, add "active" class button , remove others.
- bind change handler color picker. when happens, change background color of active button:
i'm going assume can give class of colorbutton
buttons:
$('.colorbutton').click(function(e) { e.preventdefault(); $('.colorbutton').removeclass('active'); $(this).addclass('active'); }) $('#color').change(function() { $('.colorbutton.active').css('background-color', this.value); });
working fiddle: http://jsfiddle.net/wbsab/
Comments
Post a Comment