$(window).scrollTop() vs. $(document).scrollTop()

JavascriptJqueryWindowDocumentScrolltop

Javascript Problem Overview


What's the difference between:

$(window).scrollTop()

and

$(document).scrollTop()

Thanks.

Javascript Solutions


Solution 1 - Javascript

They are both going to have the same effect.

However, as pointed out in the comments: $(window).scrollTop() is supported by more web browsers than $('html').scrollTop().

Solution 2 - Javascript

First, you need to understand the difference between window and document. The window object is a top level client side object. There is nothing above the window object. JavaScript is an object orientated language. You start with an object and apply methods to its properties or the properties of its object groups. For example, the document object is an object of the window object. To change the document's background color, you'd set the document's bgcolor property.

window.document.bgcolor = "red" 

To answer your question, There is no difference in the end result between window and document scrollTop. Both will give the same output.

Check working example at http://jsfiddle.net/7VRvj/6/

In general use document mainly to register events and use window to do things like scroll, scrollTop, and resize.

Solution 3 - Javascript

Cross browser way of doing this is

var top = ($(window).scrollTop() || $("body").scrollTop());

Solution 4 - Javascript

I've just had some of the similar problems with scrollTop described here.

In the end I got around this on Firefox and IE by using the selector $('*').scrollTop(0);

Not perfect if you have elements you don't want to effect but it gets around the Document, Body, HTML and Window disparity. If it helps...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfrenchieView Question on Stackoverflow
Solution 1 - JavascriptBodmanView Answer on Stackoverflow
Solution 2 - JavascriptHusseinView Answer on Stackoverflow
Solution 3 - Javascriptamachree tamunoemiView Answer on Stackoverflow
Solution 4 - JavascriptTapiochreView Answer on Stackoverflow