10

In Chrome and Safari, $("body").scrollTop(1000) goes where expected.

In IE and FF, nothing happens.

In IE and FF, $(window).scrollTop(1000) works, but they go to different places. It also works in Chrome and Safari, but they both go to a different place as well. They seems to be up to 300-500 pixels off.

Is there any consistent way to set the scrollTop property that works cross browser, and if not, why doesn't jQuery abstract this?

I'd like to animate it as well, which works fine in Chrome and Safari, but not in the other browsers.

Is my only option to do browser detection? (bad practice) Or is there some better way?

2
  • have you tried using $(document).scrollTop("...")?
    – epignosisx
    Jan 27, 2012 at 23:30
  • That actually worked. I had tried $('document') but that didn't. If you answer as a question I'll give you credit. Jan 27, 2012 at 23:53

3 Answers 3

11

$(jQuery.browser.webkit ? "body": "html").animate({ scrollTop: myTop }, myDur);

Webkit browsers (Chrome/Safari, both Mac and Win) use "body", others (FF/Opera/IE 7-9) use "html"

Gotta love browser detection.

1
  • 6
    jQuery.browser is deprecated since version 1.3 and removed from 1.9 Jun 26, 2013 at 7:56
6

Try

$(document).scrollTop("...");
0
0

You need to apply scrollTop to either body or html depending on the browser, but there's no harm applying it to both. Since .scrollTop() applies to the first element in the set, but .animate() applies to all elements, you can do this:

$('body, html').animate({
  scrollTop: 1000
}, 'fast');

If you want the change to apply immediately, change the speed ('fast') to 0. Alternatively, you can use the following, but I like the above syntax better:

$('body, html').each(function() { $(this).scrollTop(1000); });
1
  • Note that if animate has a call-back function, it’s executed twice. This can be a pain when pushing to the History API, et al.
    – ACJ
    Aug 16, 2018 at 12:19

Your Answer

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

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