Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you get the user’s scroll position every time they scroll with JavaScript/jQuery?

Is it possible to grab the current position of the users scroll bar when they scroll?

Say, if they were scrolled to the very top it would be 0, if they scrolled down it'd change.

Can I assign a variable to contain the current scroll position whenever I access it, or is there a function in JavaScript for this already?

like image 761
Richard Hedges Avatar asked Aug 24 '11 21:08

Richard Hedges


People also ask

How do you get the scroll position?

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 a user has scrolled to the bottom Javascript?

scroll(function() { if($(window). scrollTop() + window. innerHeight == $(document). height()) { alert("bottom!"); } });


2 Answers

There are properties on the window object for this: window.scrollX and window.scrollY.

See e.g. http://javascript.gakaa.com/window-scrollx-2-0-scrolly.aspx

like image 108
Paul D. Waite Avatar answered Oct 27 '22 01:10

Paul D. Waite


You can get the scrollTop property of the body element:

document.getElementsByTagName('body')[0].scrollTop;

This returns the number of pixels that are above the visible area.So 0 when the user hasn't scrolled, bodyheight-viewporthieght when the scrollbar is at the bottom.

like image 30
Paul Avatar answered Oct 27 '22 01:10

Paul