Search code examples
jqueryfunctionjquery-animatedirection

jquery passing in direction to animate()


I am getting the direction from the div click and a, trying to pass this into the animate function

var direction = $(this).attr('class').split(' ')[1];
var scrollAmount = 285;
$('#slider').animate({direction:'-=' + scrollAmount}, 'slow');

What is wrong?

Thanks


Solution

  • The first argument to the animate function takes in CSS properties stating the final properties for the end of the animation. You can not pass direction that way. It sounds like you either want to set the left or scrollLeft amount and to change direction then you should look at the value of direction and either use -= or += depending on the way you want to go.

    var sign;
    
    if (direction == 'left') sign = '-=';
    else sign = '+=';
    
    $('#slider').animate({left:sign + scrollAmount}, 'slow');
    

    Or if it is the property you are trying to pass

    var prop = {};
    prop[direction] = scrollAmount;
    $('#slider').animate(prop, 'slow');