*.pageYOffset, *.scrollY, *.scrollTop always logging undefined


My JS needs to know how far the user is scrolled down the page.

If I run this code:

document.addEventListener('scroll', event => console.log(document.pageYOffset));

…or do the same thing with scrollY … or scrollTop … or swap ‘document’ in for ‘window’ … the console hears the event as I scroll, but always logs ‘undefined’. This happens across multiple HTML documents, in Chrome and Firefox, whether I have any CSS reset on or not. What am I doing wrong?

>Solution :

It’s window.pageYOffset not document.pageYOffset. Refer What is the difference between window, screen, and document in JavaScript?

Leave a Reply Cancel reply