user5171262
user5171262

Reputation: 153

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?

Upvotes: 15

Views: 40115

Answers (2)

callback
callback

Reputation: 4122

For cross-browser compatibility, use window.pageYOffset

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

Upvotes: 11

BigMac
BigMac

Reputation: 342

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();

Upvotes: 31

Related Questions