231

I want to smoothly scroll down. I do not want to have to write a function for that - especially if jQuery already has one.

12 Answers 12

468

You can just use .animate() the scrollTop property, like this:

$("html, body").animate({ scrollTop: "300px" });
10
  • Very nice.. no need to use plugins for this. Feb 8, 2013 at 12:33
  • 16
    Why do you need both html and body? There is some insight here: stackoverflow.com/questions/2123690/…, but it is not a complete answer. Dec 13, 2013 at 15:22
  • 29
    body is used by webkit, html is used by firefox.
    – Jory
    Apr 1, 2014 at 17:15
  • 2
    FYI: If <html> has overflow-x:hidden; this animate will not work. (Might not work for overflow-y:hidden, and overflow:hidden, but I have not tested. Jun 9, 2015 at 15:02
  • 1
    I think body worked in Chrome as of earlier this year, but now it has to be html. Dec 8, 2017 at 19:19
73

Nick's answer works great. Be careful when specifying a complete() function inside the animate() call because it will get executed twice since you have two selectors declared (html and body).

$("html, body").animate(
    { scrollTop: "300px" },
    {
        complete : function(){
            alert('this alert will popup twice');
        }
    }
);

Here's how you can avoid the double callback.

var completeCalled = false;
$("html, body").animate(
    { scrollTop: "300px" },
    {
        complete : function(){
            if(!completeCalled){
                completeCalled = true;
                alert('this alert will popup once');
            }
        }
    }
);
6
  • 1
    The question is, why would you animate 'html, body' and not just 'body'?
    – Lior
    Oct 10, 2013 at 18:21
  • 21
    Because depending on which browser you are, you can either animate body OR html. By animating BOTH, you cover more browsers.
    – Bene
    Oct 30, 2013 at 18:21
  • But in this case it will popup really only once, also if it has to be called repeatedly (click event on button) or am I missed something?
    – HoGo
    Dec 10, 2013 at 7:23
  • Yes, in this case it will only popup once. If you need to animate repeatedly, you would make the completeCalled variable local to the callback function that executes the animate function. That way it will still popup only once when you click, but it will popup again (just once) when you click again.
    – Kita
    Jan 10, 2014 at 15:43
  • To prevent double callback function firing you can use die() function before live() function call. This guaranties, that your live() handler will be called only once. Nov 23, 2015 at 15:32
29

Nick's answer works great and the default settings are nice, but you can more fully control the scrolling by completing all of the optional settings.

here is what it looks like in the API:

.animate( properties [, duration] [, easing] [, complete] )

so you could do something like this:

.animate( 
    {scrollTop:'300px'},
    300,
    swing,
    function(){ 
       alert(animation complete! - your custom code here!); 
       } 
    )

here is the jQuery .animate function api page: http://api.jquery.com/animate/

16

Like Kita mentioned there is a problem with multiple callbacks firing when you animate on both 'html' and 'body'. Instead of animating both and blocking subsequent callbacks I prefer to use some basic feature detection and only animate the scrollTop property of a single object.

The accepted answer on this other thread gives some insight as to which object's scrollTop property we should try to animate: pageYOffset Scrolling and Animation in IE8

// UPDATE: don't use this... see below
// only use 'body' for IE8 and below
var scrollTopElement = (window.pageYOffset != null) ? 'html' : 'body';

// only animate on one element so our callback only fires once!
$(scrollTopElement).animate({ 
        scrollTop: '400px' // vertical position on the page
    },
    500, // the duration of the animation 
    function() {       
        // callback goes here...
    })
});

UPDATE - - -

The above attempt at feature detection fails. Seems like there's not a one-line way of doing it as webkit type browsers pageYOffset property always returns zero when there's a doctype. Instead, I found a way to use a promise to do a single callback for every time the animation executes.

$('html, body')
    .animate({ scrollTop: 100 })
    .promise()
    .then(function(){
        // callback code here
    })
});
2
  • 1
    Using promise() here is genius. Nov 22, 2016 at 21:32
  • This needs more upvotes. I've never seen promise used for this before, and this is something I end up searching for every few months. As Allan said, genius.
    – Tortilaman
    Apr 26, 2018 at 7:28
14

I have what I believe is a better solution than the $('html, body') hack.

It's not a one-liner, but the issue I had with $('html, body') is that if you log $(window).scrollTop() during the animation, you'll see that the value jumps all over the place, sometimes by hundreds of pixels (though I don't see anything like that happening visually). I needed the value to be predictable, so that I could cancel the animation if the user grabbed the scroll bar or twirled the mousewheel during the auto-scroll.

Here is a function will animate scrolling smoothly:

function animateScrollTop(target, duration) {
    duration = duration || 16;
    var scrollTopProxy = { value: $(window).scrollTop() };
    if (scrollTopProxy.value != target) {
        $(scrollTopProxy).animate(
            { value: target }, 
            { duration: duration, step: function (stepValue) {
                var rounded = Math.round(stepValue);
                $(window).scrollTop(rounded);
            }
        });
    }
}

Below is a more complex version that will cancel the animation on user interaction, as well as refiring until the target value is reached, which is useful when trying to set the scrollTop instantaneously (e.g. simply calling $(window).scrollTop(1000) — in my experience, this fails to work about 50% of the time.)

function animateScrollTop(target, duration) {
    duration = duration || 16;

    var $window = $(window);
    var scrollTopProxy = { value: $window.scrollTop() };
    var expectedScrollTop = scrollTopProxy.value;

    if (scrollTopProxy.value != target) {
        $(scrollTopProxy).animate(
            { value: target },
            {
                duration: duration,

                step: function (stepValue) {
                    var roundedValue = Math.round(stepValue);
                    if ($window.scrollTop() !== expectedScrollTop) {
                        // The user has tried to scroll the page
                        $(scrollTopProxy).stop();
                    }
                    $window.scrollTop(roundedValue);
                    expectedScrollTop = roundedValue;
                },

                complete: function () {
                    if ($window.scrollTop() != target) {
                        setTimeout(function () {
                            animateScrollTop(target);
                        }, 16);
                    }
                }
            }
        );
    }
}
7

I was having issues where the animation was always starting from the top of the page after a page refresh in the other examples.

I fixed this by not animating the css directly but rather calling window.scrollTo(); on each step:

$({myScrollTop:window.pageYOffset}).animate({myScrollTop:300}, {
  duration: 600,
  easing: 'swing',
  step: function(val) {
    window.scrollTo(0, val);
  }
});

This also gets around the html vs body issue as it's using cross-browser JavaScript.

Have a look at http://james.padolsey.com/javascript/fun-with-jquerys-animate/ for more information on what you can do with jQuery's animate function.

5

You can use the jQuery animation for scroll page with a specific duration:

$("html, body").animate({scrollTop: "1024px"}, 5000);

where 1024px is the scroll offset and 5000 is the duration of animations in millisecond.

1
  • Great answer! Glad you included the duration option. Just wanted to add that $("html, body").animate({scrollTop: 1024}, 5000); also works. Sep 12, 2017 at 17:59
4

Try the scrollTo plugin.

3
  • It appears that scrollTo is no longer a project at that site.
    – Jim
    Dec 3, 2013 at 20:24
  • The code to accomplish this is so simple. Why would you add a plugin to do something you can do with one line of code?
    – Gavin
    Nov 5, 2014 at 7:24
  • 5
    Four years ago it wasn't so simple.. :) Nov 12, 2014 at 1:05
4
$(".scroll-top").on("click", function(e){
   e.preventDefault();
   $("html, body").animate({scrollTop:"0"},600);
});
1

If you want to move down at the end of the page (so you don't need to scroll down to bottom) , you can use:

$('body').animate({ scrollTop: $(document).height() });
0

But if you really want to add some animation while scrolling, you can try my simple plugin (AnimateScroll) which currently supports more than 30 easing styles

-3

the cross browser code is:

$(window).scrollTop(300); 

it is without animation but works everywhere

1
  • 6
    I was looking for a way "to animate scrollTop with jQuery?" An answer that is "without animation" is not an answer. Sep 10, 2013 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.