Identify if mouse scroll is rolling up or down

Asked

Viewed 934 times

1

It is possible with Javascript to know if the mouse scroll is scrolling up or down?

2 answers

3


I believe the code below 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, means I’m rolling up, otherwise down.

this.scrollY always returns the current position scroll of window, beginning with 0, when you’re at the top of the page.

1

It is possible to do this in javascript, with the script below 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.