centree
centree

Reputation: 2439

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.

Upvotes: 70

Views: 208550

Answers (4)

adeneo
adeneo

Reputation: 318352

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

Upvotes: 34

arturmoroz
arturmoroz

Reputation: 1937

cross browser variant

$(document).scrollTop();

Upvotes: 123

Daryl Ginn
Daryl Ginn

Reputation: 1424

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

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

Upvotes: 4

Umar Farooq Khawaja
Umar Farooq Khawaja

Reputation: 3987

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

Upvotes: 1

Related Questions