How to detect scroll direction
I want to run a function when someone scrolls down on an element. Something like this:
$('div').scrollDown(function(){ alert('down') });
$('div').scrollUp(function(){ alert('up') });
But those functions don't exist. Is there a solution to this problem? Awwwards seem to be able to do it (logo in navbar changes depending on scroll direction). Unfortunately, the source code is compressed, so no luck there.
I managed to figure it out in the end, so if anyone is looking for the answer:
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.originalEvent.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#elem').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
Following example will listen to MOUSE scroll only, no touch nor trackpad scrolls.
It uses jQuery.on() (As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document).
$('#elem').on( 'DOMMouseScroll mousewheel', function ( event ) {
if( event.originalEvent.detail > 0 || event.originalEvent.wheelDelta < 0 ) { //alternative options for wheelData: wheelDeltaX & wheelDeltaY
//scroll down
console.log('Down');
} else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
Works on all browsers.
fiddle: http://jsfiddle.net/honk1/gWnNv/7/
This one deserves an update - nowadays we have the wheel
event :
$(function() {
$(window).on('wheel', function(e) {
var delta = e.originalEvent.deltaY;
if (delta > 0) $('body').text('down');
else $('body').text('up');
return false; // this line is only added so the whole page won't scroll in the demo
});
});
body {
font-size: 22px;
text-align: center;
color: white;
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Support has been pretty good on modern browsers for quite a while already :
- Chrome 31+
- Firefox 17+
- IE9+
- Opera 18+
- Safari 7+
https://developer.mozilla.org/en-US/docs/Web/Events/wheel
If deeper browser support is required, probably best to use mousewheel.js instead of messing about :
https://plugins.jquery.com/mousewheel/
$(function() {
$(window).mousewheel(function(turn, delta) {
if (delta > 0) $('body').text('up');
else $('body').text('down');
return false; // this line is only added so the whole page won't scroll in the demo
});
});
body {
font-size: 22px;
text-align: center;
color: white;
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>