I would like to ask about scroll listener. I want to add scroll listener on body but it seems doesnt work.
$('body').scroll(function(){
console.log('SCROLL BODY');
});
I create basic example on fiddle, can someone explain me why it doesn't to work? Sorry for nubies question...
I would like to ask about scroll listener. I want to add scroll listener on body but it seems doesnt work.
$('body').scroll(function(){
console.log('SCROLL BODY');
});
I create basic example on fiddle, can someone explain me why it doesn't to work? Sorry for nubies question...
Share Improve this question asked Sep 20, 2014 at 16:49 user1297783user1297783 1931 gold badge1 silver badge9 bronze badges5 Answers
Reset to default 10Try with:
$(window).scroll(function(){
console.log('SCROLL BODY');
});
This should be supported by all browsers.
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');
});
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");
};
The Pure JS Solution
Everything is very simple: just use addEventListener
for scrolling event.
document.body.addEventListener('scroll', function( event ) {
console.log(';{};');
} );
And make body
scrollable with CSS:
:root {
overflow: hidden;
}
body {
overflow-y: scroll;
max-height: 100vh;
}
I do not know why simple handler assignment doesn't work. If you know why — please, tell me.
document.body.onscroll = function( event ) {
console.log('You will never see this message.');
};
Also you could do this:
document.body.onwheel = function( e ) {
...
};
This event will be triggered only when you using a wheel (for me that wasn't obvious, actually), so if you will scroll your page with a scrollbar it will not trigger.
Why not simply using https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onscroll2
<script>
window.onscroll = function() {myFunction()};