Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add 'easing' to animate/scrolltop

Tags:

jquery

I am using the following function to create a scroll animation to anchor links:

$('a').click(function(){
    $('html, body').animate(
        {scrollTop: $( $.attr(this, 'href') ).offset().top}, 
        500 );
    return false;
});

I would like to add easing. However, when I add 'easing' after '500' it breaks the script:

$('a').click(function(){
    $('html, body').animate(
        {scrollTop: $( $.attr(this, 'href') ).offset().top}, 
        500, easing );
    return false;
});

Any ideas what I am doing wrong?

like image 923
user1444027 Avatar asked May 21 '13 21:05

user1444027


1 Answers

First you need include jQuery.UI script then your code should look:

$('a').click(function(){
    var top = $('body').find($(this).attr('href')).offset().top;
    $('html, body').animate({
        scrollTop: top
    },500, 'easeOutExpo');

    return false;
});

For your information:

Easing

The remaining parameter of .animate() is a string naming an easing function to use. An easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.


Why your code not working:

  1. Because you use this which was in scope of animation method and reference to body and html objects.
  2. Because easing is not a method. Is a string type of animation property so you need write it as string for example: 'easeOutExpo' or "easeOutExpo".
like image 187
WooCaSh Avatar answered Oct 14 '22 01:10

WooCaSh