K. Michael
K. Michael

Reputation: 75

Using variables in javascript css property

I am relatively new to Javascript, and am trying to make a simple game in which a meteor falls at a random rate. My issue is that, every time the for loop plays, the meteor div should be add math to its distance from the top, but I have no idea how to do this. Take a look at the current code and you'll see that #meteor animates with 'math'. This code doesn't work. Any ideas on how to make it work?

Thank you, input is appreciated!

var math = Math.round(Math.random * 5)
        for(var i = 0; i <= height / 3; i++) {
            $('#meteor').animate({top: "+=math"}, 1)
        }

Upvotes: 2

Views: 69

Answers (3)

Colwyn Fritze-Moor
Colwyn Fritze-Moor

Reputation: 141

A couple of things. Whenever you surround anything in JS with quotes, it is treated as a string, so even though you have the variable math, because it is in quotes it is treated as the string 'math'. The other thing is += has to have something come before it in order to work and can't be used with jQuery in the way you're trying to.

To simple get your code working, change it to this:

var math = Math.round(Math.random * 5)
for(var i = 0; i <= height / 3; i++) {
    // Gives the 'top' value for meteor. parseInt removes the
    // 'px' that will show up on the end and return type int
    var meteorTop = parseInt($('#meteor').css('top')); 
    $('#meteor').animate({top: meteorTop + math}, 1);
}

That said, your animations are going to overlap and you're going to want to wait between animations or else they will trigger on top of each other and not work the way you want them to.

Only kind of related, a situation in which += works is this:

var int = 0;
int += 2; // int = 2; this is the same as: int = int + 2;
int += 3; // int = 5; this is the same as: int = int + 3;

You should add the same type to itself, JS will do some interpretation for you, but you should always use += with the same type. string += string or int += int.

Upvotes: 3

RobG
RobG

Reputation: 147403

If you are trying to increment the value of top by math on each iteration, then you want something like:

  $('#meteor').animate({top: math * i}, 1)

Upvotes: 0

Hitesh Siddhapura
Hitesh Siddhapura

Reputation: 1392

try following one

 for(var i = 0; i <= height / 3; i++) {
    var math = Math.round(Math.random * 5)
    $('#meteor').animate({top: "+="+math}, 1);
 }

Upvotes: 0

Related Questions