Get scroll position with jquery

Strange query, but I need to get the current scroll position of the browser as a variable. Which js or jquery function should i use? I need to figure out which elements to display on the side. I found several things on the Internet, but nothing works for my div, just a full page.

+61
javascript jquery
Feb 14 '13 at 23:37
source share
4 answers

cross browser option

$(document).scrollTop(); 
+104
Aug 02 '13 at 11:05 on
source share

Older IE and Firefox browsers attach a scrollbar to documentElement , or the <html> in HTML.

All other browsers attach a scrollbar to document.body , or the <body> in HTML.

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

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

jQuery makes this a little easier when passing to a window or document jQuery scrollTop does a similar check and computes it, so any of them should work in a 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 each matched element.




... nothing works for my div, just a full page

If this is for a DIV, you will need to target an element with an attached scrollbar to get the scroll amount

 $('div').scrollTop(); 

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

 $('div').offset().top 
+30
Feb 14 '13 at 23:39
source share

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

 var pos = $('body').scrollTop(); 
+3
Feb 14 '13 at 23:41
source share

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

+1
Feb 14 '13 at 23:39
source share



All Articles