kempchee
kempchee

Reputation: 470

Function Call ordering in jQuery

I am using java-query to generate a chess board on page load:

Basically I have an empty body:

<body>
</body>

I then have the following javascript linked:

var addsquareblack=function(i,row){$(document).ready(function(){

    var square=$('<div class="square"></div>');
    if ((i%2)===0)
        {square.css('background-color','brown');}
    $('.row').last().append(square);
});};

var addsquarewhite=function(i,row){$(document).ready(function(){

    var square=$('<div class="square"></div>');
    if ((i%2)===0)
        {square.css('background-color','white');}
        else
        {square.css('background-color','brown');}
    $('.row').last().append(square);
});};

var create=function(a){$(document).ready(function(){
    var row=$('<div class="row"></div>');
    $('body').append(row);
    if ((a%2)===0)
    {for(var i=1;i<9;i++){addsquareblack(i,row);}}
    else
    {for(var i=1;i<9;i++){addsquarewhite(i,row);}}
});};

var addrows=function(){
    for(var i=1;i<9;i++){create(i);}
    };

I then call in a script in head:

<script> addrows() </script>

However, the addsquarewhite and addsquare black are not functioning properly: My divs with class row are being added to body correctly, but then all of the squares that I am adding are getting bunched into the very last div. I thought that they would get added only to the last div available at the time of the method call. Clearly I don't understand something about scope/flow in javascript. Please enlighten.
Thanks!

Upvotes: 0

Views: 76

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Also your usage on ready handler is wrong

It is because you are adding the square elements to the last row instead of the row.

$('.row').last().append(square)

instead

var addsquareblack=function(i,row){
    var square=$('<div class="square">1</div>');
    if ((i%2)===0) {
        square.css('background-color','brown');
    }
    row.append(square);
};

var addsquarewhite=function(i,row){
    var square=$('<div class="square">2</div>');
    if ((i%2)===0) {
        square.css('background-color','white');
    } else {
        square.css('background-color','brown');
    }
    row.append(square);
};

var create=function(a){

    var row=$('<div class="row"></div>');
    $('body').append(row);
    if ((a%2)===0) {
        for(var i=1;i<9;i++){
            addsquareblack(i,row);
        }
    } else {
        for(var i=1;i<9;i++){
            addsquarewhite(i,row);
        }
    }

};

var addrows=function(){
    for(var i=1;i<9;i++){
        create(i);
    }
};
$(document).ready(function(){
    addrows();
});

Demo: Fiddle

Upvotes: 1

Related Questions