36

Before i tear my hair out and go down the wrong path in terms of debugging. Can someone confirm that this code will do as intended. Ie. animate 5 divs to different positions:

var i, j, k;
$('#menuButton').click(function(){
    for (i=1; j=0; k=150; i<=5; i++; j+=30; k-=30){
        $('.spinner #item' + i).animate({
            left: '+=' + j,
            bottom: '+=' + k
          }, 500, function() {
            // Animation complete.
        });
    }
});

When i click the #menuButton, nothing happens and I get this error:

Uncaught SyntaxError: Unexpected token ; on the 'for()' line...

8
  • 2
    A for loop only takes three expressions. You probably want , between variable assignments. The ; are for separating the initial assignment, condition, and the expression to run after each iteration. Commented Dec 1, 2011 at 21:54
  • Why increment three different variables rather than increment one and multiply by it for the other values? jsfiddle.net/jasper/7fkx7/2 Commented Dec 1, 2011 at 22:01
  • @Jasper I like this a lot but it doesnt quite fit my requirements, i need the values to start at the ones i defined... Commented Dec 1, 2011 at 22:07
  • @benhowdle89 Gotcha. I see how this syntax is easy to use in that case. But you can add the initial value to each of the multiplications: jsfiddle.net/jasper/7fkx7/3. bottom : '+=' + (i * -30 + 150). It's like they teach you in algebra in High School for the equation of a line :)... ax+c (where c is your constant and a is your slope/rate) Commented Dec 1, 2011 at 22:11
  • @Jasper Fantastic!!! Out of interest, how would i apply a slightly more curved effect, rather than just in one line... Commented Dec 1, 2011 at 22:13

3 Answers 3

59

You've got some semicolons where you want commas:

for (i=1, j=0, k=150; i<=5; i++, j+=30, k-=30) { /* do work */ }

You should only have three "statements" inside your for

for( [init]; [test]; [increments]) { [block] }

To do multiple [inits] or [increments] you have to use the sometimes magical, but oft forgotten, comma operator

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

Comments

16

too much semicolons there

for (i=1; j=0; k=150; i<=5; i++; j+=30; k-=30){

should be

for (i=1, j=0, k=150; i<=5; i++, j+=30, k-=30){

Comments

2

You made gramatical errors in your code that you could have easily spotted had you used static code analysis tools such as the lovely JSHint.

In addition, you should further understand the use of the comma operator in JavaScript, our site has a few answers on it already.

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.