Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is $( window scrollTop ()?

jQuery scrollTop() Method The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0.

What is document scrollTop?

The Element. scrollTop property gets or sets the number of pixels that an element's content is scrolled vertically. An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content.

Is scrollTop deprecated?

scrollTop is deprecated in strict mode.

Can I use document documentElement scrollTop?

Generally you can use (document. documentElement. scrollTop || document. body.


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().


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.


Cross browser way of doing this is

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