0

I have a couple of divs that show colors. When I click on a div, it is not showing the right color. It shows only the last color #000000

var color = ["#003366", "#336699", "#3366CC", "#003399", "#000099", "#0000CC", "#666666", "#333333", "#000000"];
var i = 0;
for (; color[i];) {
    var theme = "#theme" + i;
    var text = color[i];
    $(theme).click(function() {
        $("#title_content").css('background-image', '');
        $("#content_text").css('background-image', '');
        $("#title_content").css('background-color', text);
        $("#content_text").css('background-color', text);
    });
    i++;
}
Leonid Glanz
  • 1,261
  • 2
  • 16
  • 36
hans
  • 29
  • 1
  • 6

1 Answers1

1

You can associate color with element using .data() which can be fetched later.

Here's an example, in which I have added a common class to use it as selector.

var color = ["#003366", "#336699", "#3366CC", "#003399", "#000099", "#0000CC", "#666666", "#333333", "#000000"];

for (var i = 0; i < color.length;i++) {
    $("#theme" + i)
    .addClass('selectorClass') //Add class for binding event
    .data('color', color[i]); //Associate color with element        
}


//Bind Event
$('.selectorClass').click(function() {
    $("#title_content").css('background-image', '');
    $("#content_text").css('background-image', '');

    //Fetch the color using this
    var text = $(this).data('color');
    $("#title_content").css('background-color', text);
    $("#content_text").css('background-color', text);
});
Satpal
  • 132,252
  • 13
  • 159
  • 168