Modo Modo
Modo Modo

Reputation: 123

Color picker set individual attribute in JQuery each

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

Answers (2)

Jason P
Jason P

Reputation: 27012

Your solution seems overly complex. A simpler solution might be this:

  1. Add click handlers to the buttons. When a button is clicked, add an "active" class to that button and remove from others.
  2. Bind a change handler to the color picker. When that happens, change the background color of the active button:

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

Giwrgos Tsopanoglou
Giwrgos Tsopanoglou

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

Related Questions