Reputation: 426
I place below line of code within a loop,
for ( var i=1; i<=10; i++ ) {
var left = 0;
left += 20;
$('#item'+i).css({
'left': left
});
}
how can I make left value increment by 20? currently all is set to 20, it won't increase by 20.
Upvotes: 0
Views: 796
Reputation: 8033
For this purpose, you need to get css left first, then increment and assign it:
for ( var i=1; i<=10; i++ ) {
var left = $('#item'+i).css('left');
left.replace("px", ""); //remove "px" from left. for example, convert "30px" to "30"
left = parseInt(left); //convert to integer
left += 20;
$('#item'+i).css({ 'left': left+"px" });
}
Upvotes: 0
Reputation: 166
var left = 0;
for ( var i=1; i<=10; i++ ) {
left += 20;
$('#item'+i).css({ 'left': left }); }
Everytime you go in the loop, var left is initialized to 0. Thus your value will always be 20. move the initialization outside the loop. It should work as expected.
Upvotes: 1