Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get scroll position in Javascript

I would like to retrieve the current scroll position in Javascript, after some research I found this: window.scrollY and window.scollTop.

But the problem is that it does not work 100% on all browsers, is there something more reliable?

like image 441
user5171262 Avatar asked Jul 29 '15 22:07

user5171262


2 Answers

The solution for JavaScript is:

var scrollPos = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop;

Or if you use jQuery (this is more reliable, due cross-browser support):

var scrollPos = $(window).scrollTop();
like image 156
BigMac Avatar answered Nov 16 '22 00:11

BigMac


For cross-browser compatibility, use window.pageYOffset

https://developer.mozilla.org/en-US/docs/Web/API/Window/pageYOffset

like image 10
callback Avatar answered Nov 15 '22 23:11

callback