Armin Bu
Armin Bu

Reputation: 1360

Changing background-color from separately elements from an array (jQuery)

this is my code:

$(document).ready(function() {      
    for( var i = 0 ; i < 8 ; i++ ){
        for( var j = 0 ; j < 8 ; j++ ){
            var $class = getPieceName(board[i][j][0])
            $(.$class ????).click(function() {
                $(this).css('background-color', 'red');     
            });
        }
    }           
});

As you can see, I want to change the background color of an element. The for-loops are needed to get the element, in an array, which the user clicked on. How to write the variable ($class) as a class?

Upvotes: 1

Views: 619

Answers (4)

TheDeadSerious
TheDeadSerious

Reputation: 862

It might be simpler to apply a class or data-attribute to all your board pieces, like class="board_piece" data-board-x="1" data-board-y="2" and then bind the click handler to a selector for that:

$('.board_piece').click(function() { $(this).css(...) }

You could use the data-board-x and -y coordinates I added to retrieve the actual position within the board inside your click handler.

Upvotes: 0

verbanicm
verbanicm

Reputation: 2526

If class is a string you can use it like this:

$("." + $class).click(function(){ ... });

Upvotes: 2

Balint Bako
Balint Bako

Reputation: 2560

It think all you need is '.' + $class

Upvotes: 1

Brad
Brad

Reputation: 6332

you can name your variable then concat it into your selector since its a string not a JQ object.

var class = getPieceName(board[i][j][0])
     $('.' + class).click(function() {

Upvotes: 2

Related Questions