Jezen Thomas
Jezen Thomas

Reputation: 13800

Passing arguments to functions

I don't see anything wrong with this code, but it's not working as expected.

function slide(slideIndex, slideDirection) {
    console.log(slideDirection); // outputs 'right'
    $('.slide').animate({slideDirection: '-=940'}, 400);
}    

$(function(){
    $('.prev','.slide').click(function (e) {
        e.preventDefault();

        var slideIndex = $(this).closest('.slide').index(),
            slideDirection = 'right';

    slide(slideIndex, slideDirection);
    });
});

If I use just the string 'right' in the animate method, it works. What am I doing wrong?

Upvotes: 0

Views: 70

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

You're creating an object literal with the property called slideDirection, you're not using the value of the argument. To do that, you'll need to create an object in 2 steps, separately:

var obj ={};//empty object literal
obj[slideDirection] = '-=940';//assign a new property
$('.slide').animate(obj, 400);

That should do the trick. Your object, in json format looks like this: {"slideDirection":"-=940"} whereas mine (or the object created as I explained) looks like this: {"right":"-=940"}. The latter is what you need, if I'm not mistaken

Upvotes: 5

Related Questions