Thursday, May 3, 2012

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


What's the difference between:




$(window).scrollTop()



and




$(document).scrollTop()



Thanks.



Source: Tips4all

2 comments:

  1. They are both going to have the same effect.

    Both scroll to the top of the object, an html document is considered the "document" thus scrolling to the top of the html page. A "window" object is created with each frame, thus your main window is one frame, if you had an "iframe" that would create another window object. So your just scrolling to the top of the window object, creating the same effect.

    It seems that the window object is buggy when it comes to this. It apprently does not work in IE8 and Opera, so it is best to use $(html)scrollTop().

    ReplyDelete
  2. 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 it's properties or the properties of it's 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.

    ReplyDelete