KevinTale
KevinTale

Reputation: 1858

Cant use .animate() jQuery function into another function

I have created a function names isMoving() within I use an animate Jquery function with direction as parameter. Below in the code, I use the isMoving() function and type either "right/left/top/bottom" in order to make the animate works. But it doesnt, it just ignore it. However, if I try to type any direction in the animate function in isMoving(), it works fine. Any idea on what's going on here ?

Here is the code :

Player.prototype.isMoving = function(direction, x, y) {
    //I want to use animate on player in 4 differents cases. Top, Bottom, Left, Right. So I try to use direction as parameter but and I execute the function (below on the code) it just doesn't work. However If I try to write "left" on the animate just below, it will work.
    player.animate({direction: "60px"}, 500, function (){
        *Code...*
    }); 
}

Player.prototype.isGoingTo = function (direction, onMove) {
    *Code...*
       switch (direction) {
        case 'left':
            newX -= 1;
            **this.isMoving('right', newX, newY);**
            break;
        case 'right' :
            newX += 1;
            **this.isMoving('left', newX, newY);**
            break;
        case 'top':
            newY -= 1;
            **this.isMoving('bottom', newX, newY);**
            break;

        case 'bottom' :
            newY += 1;
            **this.isMoving('top', newX, newY);**
            break;
        }
    }

Thanks.

Upvotes: 1

Views: 39

Answers (1)

shershen
shershen

Reputation: 9993

It's because JS cannot create object in that fashion {direction: "60px"} when direction is a variable. You have to first create an object with correct key and the use it in the player.animate function like this:

Player.prototype.isMoving = function(direction, x, y) {
var obj = {};
obj[direction] = '60px';
  player.animate(obj, 500, function (){
    *Code...*
  }); 
}

Upvotes: 1

Related Questions