27

I got a solution from stackoverflow to scroll to the top of the page like

$('html, body').animate({scrollTop: $("#page").offset().top}, 2000);

But I am not sure why to use 'html, body' for scrollTop instead of just 'html' ?

Brad
  • 159,648
  • 54
  • 349
  • 530
Hector Barbossa
  • 5,506
  • 13
  • 48
  • 70

1 Answers1

27

Some browsers apply the "overall" scroll to document.documentElement (the <html> element) and others to document.body (the <body> element). For compatibility with both, you have to apply the scrolling to both.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • I'm wondering if you know which browsers doesn't support the scroll over the `body` because I can not find out anyone right now. Do you have any link which explains or gives more information about your answer? – Alvaro Sep 19 '13 at 09:33
  • No, sorry, but you can easily find out: Put `document.body.scrollTop = 100` in your console, and if the page scrolls then it means the browser you're on uses the body. – Niet the Dark Absol Sep 19 '13 at 09:50
  • 1
    In addition the @Alvarao's query, I'm also interested whether one of these behaviours violates spec or if both are permitted. – Mark Amery Jan 07 '14 at 13:26
  • 18
    This is troublesome, because callbacks then fire twice. – Costa Michailidis Jun 04 '14 at 02:46
  • 2
    @Synexis You can also [debounce](http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/) the callback function instead. – Niet the Dark Absol Aug 18 '14 at 03:16
  • @NiettheDarkAbsol That is a much better solution. Mine would cause some browsers to ignore the callback. I need to not comment here when tired. Cheers. (my comment which was to immediately return the callback if the node name was BODY, not a good idea, deleted that comment and leaving this one for reference) – Synexis Aug 19 '14 at 06:55
  • I've found that Firefox uses html scrollTop. – vbezhenar Sep 04 '14 at 11:09
  • 2
    I haven't tested exhaustively, but it looks like Firefox (at version 41) and IE11 still use `document.documentElement` aka `` as the outermost scroll parent. Edge, Chrome and Safari all scroll the main page via `document.body`. – natevw Oct 29 '15 at 23:36