Scroll listener on body

断了今生、忘了曾经 提交于 2019-11-30 20:25:27

Try with:

$(window).scroll(function(){
  console.log('SCROLL BODY');
});

This should be supported by all browsers.

All the answers above expect jQuery being the framework of use. A framework agnostic / plain JS implementation could look like this

ES 5:

// ES 5 :
document.getElementsByTagName('body')[0].onscroll = function() {
    console.log("scrolling");
};

ES 6 (and above) :

// ES 6 (and above)
document.getElementsByTagName('body')[0].onscroll = () => {
    console.log("scrolling");
};

Because the body isn't scrolling, the window is.

In This example, you'll see that the event listener bound to the parent container is what's firing, because that element is the one that's actually scrolling.

The HTML looks like this:

<div id="container">
    <p id="content">some text</p>
</div>

The CSS looks like this:

#container {
    height: 200px;
    overflow-y: scroll;
}

#content {
    height: 1000px;
}

And the relevant JS looks like this:

$('#container').on('scroll', function() {
    console.log('#container');
});

$('#content').on('scroll', function() {
    console.log('#content');
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!