Get scroll position using jquery

JavascriptJquery

Javascript Problem Overview


Strange request, but I need to get the current browser scroll position as a variable. What js or jquery function should I use? I need it to figure out what elements to display on the side. I've found a few things online but nothing that works for my div, just the full page.

Javascript Solutions


Solution 1 - Javascript

cross browser variant

$(document).scrollTop();

Solution 2 - Javascript

Older IE and Firefox browsers attach the scrollbar to the documentElement, or what would be the <html> tag in HTML.

All other browsers attach the scrollbar to document.body, or what would be the <body> tag in HTML.

The correct solution would be to check which one to use, depending on browser

var doc = document.documentElement.clientHeight ? document.documentElement : document.body;
var s   = $(doc).scrollTop();

jQuery does make this a little easier, when passing in either window or document jQuery's scrollTop does a similar check and figures it out, so either of these should work cross-browser

var s = $(document).scrollTop();

or

var s = $(window).scrollTop();

jQuery scrollTop() docs

> Description: Get the current vertical position of the scroll bar for > the first element in the set of matched elements or set the vertical > position of the scroll bar for every matched element.


> ...nothing that works for my div, just the full page

If it's for a DIV, you'd have to target the element that has the scrollbar attached, to get the scrolled amount

$('div').scrollTop();

If you need to get the elements distance from the top of the document, you can also do

$('div').offset().top

Solution 3 - Javascript

I believe the best method with jQuery is using .scrollTop():

var pos = $('body').scrollTop();

Solution 4 - Javascript

Use scrollTop() to get or set the scroll position.

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
QuestioncentreeView Question on Stackoverflow
Solution 1 - JavascriptarturmorozView Answer on Stackoverflow
Solution 2 - JavascriptadeneoView Answer on Stackoverflow
Solution 3 - JavascriptDaryl GinnView Answer on Stackoverflow
Solution 4 - JavascriptUmar Farooq KhawajaView Answer on Stackoverflow