1

I would like to trigger something once (and only once) a user has scrolled down 100 pixels from the top.

In the past I was given this code, but it doesn't seem to be working?

window.onscroll = function() {
  var scrollLimit = 100;
  var scrollValue = document.body.scrollTop;
  if (scrollValue >= scrollLimit) {
    alert("x")
  }
};
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
jeremy
  • 105
  • 10
  • Thanks a lot for the replies. Someone posted the following code (which I slightly edited), with : document.documentElement.scrollTop and it works fine. I dont know why it had been deleted : doesnt work with ie? – jeremy Jun 06 '18 at 13:35

3 Answers3

2

You are using the wrong property here.

Instead of scrollTop property you need to use the Window.scrollY property.

This is how should be your code:

window.onscroll = function() {
  var scrollLimit = 100;
  if (window.scrollY >= scrollLimit) {
    alert("x")
  }
};

Note:

window.scrollY compatibility issues with IE:

Unfortunately window.scrollY doesn't work with IE browsers, for IE you can use window.pageYOffsetas a replacement, but it always gives hundreds rounded values (100, 200, 300, ...).

Otherwise you can check the accepted answer here it uses document.documentElement.scrollTop as a workaround.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • It seems that "Window.scrollY" is not compatible with ie – jeremy Jun 06 '18 at 13:35
  • @jeremy Yes, but you can use `window.pageYOffset`as a replacement in IE, but it always gives hundreds rounded values, or you can check the [accepted answer **here**](https://stackoverflow.com/questions/16618785/ie8-alternative-to-window-scrolly) it uses `document.documentElement.scrollTop` as a workaround. – cнŝdk Jun 06 '18 at 13:42
1

Try this:

var scrollValue = window.scrollY;
1

scrollTop will give you the offset between the top of the element and the top of the document. Since the body of a html document by default starts at the top of the document, body.scrollTop always stays 0 unless you specifically used css to make the body not start at the top.

So you have to use scrollY instead of scrollTop. If the browser you use does not support scrollY ( eg. IE ) you can try pageYOffset.

Shilly
  • 8,511
  • 1
  • 18
  • 24