[javascript] Get scroll position using jquery

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.

This question is related to javascript jquery

The answer is


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

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

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

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