Reputation: 123
I have three buttons on a page I've set up as an array. I'm using $.each to iterate through them and inside that is the color picker function. I'm trying to have only the (last) clicked button change background color, but right now, if I click all 3 before using the color picker, they all change color. I need the button last clicked only to 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)
});
Upvotes: 0
Views: 137
Reputation: 27012
Your solution seems overly complex. A simpler solution might be this:
I'm also going to assume you can give a class of colorButton
to the 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/
Upvotes: 1
Reputation: 1215
Why don't you bind the click event with the color change?
$('.buttons_that_change_color_on_click').bind('click', function(){
this.style.backgroundcolor = the_value_you_want;
});
Upvotes: 0