Use the addEventListener
method on the window
object. Example:
window.addEventListener("scroll", function() { var msg = 'html.scrolltop is ' + document.getElementsByTagName('html')[0].scrollTop + '<br>'; msg += 'body.scrolltop is ' + document.body.scrollTop + '<br>'; msg += 'pageYOffset is ' + window.pageYOffset + '<br>'; document.getElementById('debug').innerHTML = msg; });
jQuery is useful to abstract away the browser differences, but if you want a pure Javascript way, and you don’t need to support IE8 or older, then this works:
var currentScrollAmount = window.pageYOffset