0

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.

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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" }); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.