28

For example, to scroll to a certain element on the page (ie here: How to go to a specific element on page?)

$("#fromTHIS").click(function() {
    $("html, body").animate({ scrollTop: $("#toTHIS").offset().top }, 500);
    return true;
});

I've tried both and they both look that they are doing the job. What am I missing?

Community
  • 1
  • 1
Lior
  • 40,466
  • 12
  • 38
  • 40

3 Answers3

28

The reason you use a selector for BOTH $('html, body') is because of web browser inconsistency. After a few tests I have found three things:

  1. The browsers Firefox & IE utilize the html portion of this selector
  2. Browsers in the "webkit class" eg: Safari and Chrome respond to the body.
  3. Although one can avoid the issue all together by using $(document) instead.

There's also a ticket on the jQuery bug tracker specifically stating this issue here

Joe
  • 2,085
  • 1
  • 18
  • 28
  • thanks for this @Joe! One confusion i have is about the 3rd suggestion. from what I see $(document) selects really a wrapper around the html tag - $(document)[0].children[0]==... why wouldnt that be the same as $('html')? – Lior Nov 07 '13 at 15:50
  • 2
    Unfortunately your solution does not work on FF v30.0. What a bummer! – Steve C Jul 21 '14 at 14:33
  • `$("html, body").animate({ scrollTop: 400 }, 500);` is working right now on this very page in my FF30? maybe you have some sort of conflict? – Joe Jul 21 '14 at 15:34
  • 1
    Looks like jQuery either took down the ticket or changed the link... looking into getting an update for this answer – Joe Jun 16 '15 at 19:30
  • 3
    @Joe, as steve mentioned, $(document) it not working in Firefox. I tried with $('html,body') and it works. But using the document and it does nothing. You should scratch your *3rd thing*. – Alexis Wilke Feb 20 '16 at 07:57
  • This approach is particularly annoying if you're using the 'done/success' event handler for this animation, which gets executed twice, regardless of which selector works for your browser. – Troy Niemeier Sep 08 '22 at 19:19
0

$('html, body') seems to be the jquery solution for cross-browser scroll animation.

If you want a cross browser solution without animation, you can go ahead and try this:

$(window).scrollTop(0);
// Accepts int of pixels.

Tested it on latest Chrome, Opera and FF. Seems to work cross browser. (Unless someone can confirm that it doesn't work on IE or Safari or others)

Read more about jQuery scrollTop.

evilReiko
  • 19,501
  • 24
  • 86
  • 102
0

Here is an example for cross browser animation:

//('html, body') is the jquery solution for cross-browser scroll animation
$('html, body').animate({
    scrollTop: $(".abc-container").offset().top+ "-50px"
}, 300)
JON
  • 965
  • 2
  • 10
  • 28
Arjjun
  • 1,203
  • 16
  • 15