48

I'd like my page to go to the top when certain anchor is clicked.

Here is how I tried to do it but it's not working, it's scrolling super fast.

 $('a[href=#top]').click(function () {
        $('body').animate({
                scrollTop: 0
        },
        50);
});

I want to slow it down.

random
  • 9,774
  • 10
  • 66
  • 83
Gandalf StormCrow
  • 25,788
  • 70
  • 174
  • 263

4 Answers4

114
$('a[href=#top]').click(function(){
    $('html, body').animate({scrollTop:0}, 'slow');
});

Perhaps?

pimvdb
  • 151,816
  • 78
  • 307
  • 352
ant
  • 22,634
  • 36
  • 132
  • 182
  • 1
    Any idea why `$('html, body')` is required? I tried it with `$(window)`, but it didn’t seem to have any effect, which I kind of expected it to seeing as (if I remember correctly) it’s the window object that keeps track of the scroll position? – Paul D. Waite Mar 21 '12 at 11:30
  • 6
    window is veiwport but you need to animate the document html, also you don't need body $("html").animate({scrollTop: $("#whatever_id_you_want_to_go_to").offset().top}, 1200); – fullstacklife May 03 '12 at 16:49
  • 2
    I think you do need `body` as `html` won't work in all browsers. – Simon East Sep 21 '12 at 02:04
  • so you need both body and html to support all browsers? – chovy May 07 '13 at 01:21
  • How about adding [`preventDefault`](http://api.jquery.com/event.preventDefault/) to prevent flashing of page before scrolling to top? –  Jul 22 '13 at 10:03
  • 4
    body is used by webkit browsers, html is used by firefox. – Jory Apr 01 '14 at 17:14
  • As of now Chrome and Safari seem to work fine with just html. – dmnd Jul 29 '14 at 21:47
  • @dmnd Are you sure? It's not working for me in Chrome 50.0.2661.94. I'm testing with this: https://jsfiddle.net/8uswq8u3/ – Adam Taylor May 03 '16 at 17:31
  • @AdamTaylor this answer is more than 6 years old, probably some things have changed – ant May 05 '16 at 16:07
  • @ant I wasn't responding to the answer; I was responding to a comment that was made less than two years ago. – Adam Taylor May 05 '16 at 16:48
  • Better to be safe then sorry and use html & body, using both shouldn't cause any hiccups. – brandito Apr 18 '18 at 02:38
  • Just FYI: These days it would be likely best if you did `$(document.scrollingElement)`, because there is such a prop these days. – Robert Koritnik Nov 20 '18 at 09:43
10

When you pass 50 as the second parameter to animate, that is 50 milliseconds. See the animate documentation. Either pass a larger number, or as c0mrade suggested, simply pass 'slow' .

wsanville
  • 37,158
  • 8
  • 76
  • 101
0

you can set the time for scroll top

$('a[href=#top]').click(function(){
 $('body').animate({
     scrollTop: 0},4000);});
Gireesh T
  • 57
  • 1
  • 9
0
$('a[href=\\#top]').click(function(){
  $('body').animate(
    {
      scrollTop: 0
    }, 
    2000
  );
});

The # should be escaped \\#.

Yassine Khachlek
  • 1,134
  • 12
  • 17