Ohnegott
Ohnegott

Reputation: 313

function inside javascript loop

I'm having trouble understanding this problem. I'm assuming its a scope issue, but I don't know how to get around it.

I created an array to store the x and y positions of 6 separate elements

var pos = new Array();
for(i=1;i<7;i++){
    pos['box'+i] = $('.box'+i).position();
}

I would like to then add this to each element with another loop

for(i=1;i<7;i++){
    $('.box'+i).draggable({zIndex: 9999, revert: function(){
        $(this).animate({top:pos['box'+i].top, left:pos['box'+i].left}, 500, "easeOutElastic");
    }});
}

The dragging works, but the revert function doesn't. With some alerts I found that it is trying to get the position of pos['box7'] which doesn't exist. Why isn't it adding each 'box'+i ?

Upvotes: 3

Views: 490

Answers (1)

Jord&#227;o
Jord&#227;o

Reputation: 56537

Try to encapsulate the code inside the loop in a new "context":

(function(i) {
  .. your code
})(i);

Upvotes: 1

Related Questions