Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrollTop() returns 0 in chrome

I want to check if page is scrolled after it has finished loading and I'm using this code:

$(document).ready(function(){   
    alert($(window).scrollTop());
});

It works well in Firefox but allways returns 0 in Chrome. Why is this?

like image 381
Mihnea Belcin Avatar asked Oct 19 '11 09:10

Mihnea Belcin


People also ask

What does scrollTop return?

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. When used to return the position: This method returns the vertical position of the scrollbar for the FIRST matched element.

Is scrollTop deprecated?

scrollTop (and body. scrollLeft ) are deprecated in ES5 strict-mode.

How do you get the scrollTop of an element?

To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.

How do you check if scrollbar is at the bottom?

You find the height of the scrolling container, then compare that to the scroll position. If they are the same, then you have reached the bottom.


2 Answers

Actually Firefox is the only browser that doesn't return 0 for $(window).scrollTop() on domReady or window.onload. Chrome, Safari and IE all return 0. The only safe way to get correct position of scrollbar on domReady is, as mentioned in another answer above, to set an event handler on window's scroll event as below:

$(document).ready(function(){   
    $(window).scroll(function() {
        console.log($(window).scrollTop());
        $(window).unbind('scroll');
    });
});
like image 114
smohadjer Avatar answered Oct 13 '22 03:10

smohadjer


$(window).scrollTop() will return 0 when the window isn't scrollable.

like image 34
mmcnickle Avatar answered Oct 13 '22 04:10

mmcnickle