5

See http://codepen.io/anon/pen/NGqPNz

CSS:

html {
  height: 100%;
  overflow-y: hidden;
}
body {
  height: 100%;
  overflow-y: auto;
}

JS:

  $('body').bind("scroll", function () {
    if ($('body').scrollTop()) {
      console.log('triggered!');
    } else {
      console.log($('body').scrollTop());
    }
  });

The scroll event is firing on the body element. The scroll bar is on the body element, not on the html or the window element. So why does document.body.scrollTop or $('body').scrollTop() return 0?

Is there any way I can detect the scroll bar position with this or am I stuck if I want to use height: 100%; overflow:hidden on the html element?

Thanks!

tdj
  • 143
  • 1
  • 1
  • 7
  • I think it's a webkit bug. Works with Firefox. https://code.google.com/p/chromium/issues/detail?id=423935 – Shikkediel Sep 07 '15 at 02:41
  • Thanks! I set body to overflow-y hidden and added a wrapper div with height 100 and overflow-y auto, and the scroll event / scrollTop works on the div. – tdj Sep 07 '15 at 13:24

2 Answers2

6

Thanks to Shikkediel's comment, it appears to be a Webkit bug. If you put a div immediately inside the body, and bind the scroll event to the div, it works.

http://codepen.io/anon/pen/bVderq

CSS:

html {
  height: 100%;
  overflow-y: hidden;
}
body {
  height: 100%;
  overflow-y: hidden;
}
.scroll-wrapper {
  height: 100%;
  overflow-y: auto;
}

JS:

$('.scroll-wrapper').bind("scroll", function () {
  if ($('.scroll-wrapper').scrollTop()) {
    console.log('triggered!');
    console.log($('.scroll-wrapper').scrollTop());
  } else {
    console.log($('.scroll-wrapper').scrollTop());
  }
});
tdj
  • 143
  • 1
  • 1
  • 7
4

It's because you have overflow-y: hidden;. Remove this and then scrollTop() will work

Chanckjh
  • 2,587
  • 2
  • 22
  • 28