Is it possible with Javascript to know if the scroll of the mouse is scrolling up or down?
Is it possible with Javascript to know if the scroll of the mouse is scrolling up or down?
I believe the following code can help:
var lastScrollTop = 0;
window.addEventListener('scroll', function (e) {
// mesma posição
if (e.scrollY === lastScrollTop) return;
console.log(this.scrollY < lastScrollTop ? "Cima" : "Baixo")
lastScrollTop = this.scrollY;
}, true)
Basically, I always save the last position of the current scroll. When the previous value is less than the current value of scrollY
, it means that I'm rolling up, otherwise down.
this.scrollY
always returns the current position scroll
of window
, starting from 0
, when it is at the top of the page.
It is possible to do this in javascript, with the following script you can identify in console.log
:
<script>
var body = document.getElementsByTagName("body")[0];
if (body.addEventListener) {
// IE9, Chrome, Safari, Opera
body.addEventListener("mousewheel", detectarDirecaoRolagem, false);
// Firefox
body.addEventListener("DOMMouseScroll", detectarDirecaoRolagem, false);
}
function detectarDirecaoRolagem( e )
{
var delta = null,
direction = false
;
if ( !e ) {
e = window.event;
}
if ( e.wheelDelta ) { // funciona na maioria dos casos
delta = e.wheelDelta / 60;
} else if ( e.detail ) { // funciona no Firefox
delta = -e.detail / 2;
}
if ( delta !== null ) {
direction = delta > 0 ? 'cima' : 'baixo';
}
console.log(direction);
return direction;
}
</script>