Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain why scrollTop() always returns 0 here

Tags:

jquery

css

scroll

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!

like image 991
tdj Avatar asked Sep 07 '15 01:09

tdj


2 Answers

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());
  }
});
like image 159
tdj Avatar answered Nov 01 '22 01:11

tdj


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

like image 36
Chanckjh Avatar answered Nov 01 '22 02:11

Chanckjh