Home > other >  Horizontal scrolling with mouse wheel in vanilla JS
Horizontal scrolling with mouse wheel in vanilla JS

Time:01-13

I'm trying to migrate some jQuery code to vanilla JS that modifies the mouse wheel behavior to scroll a site horizontally instead of vertically:

jQuery:

var wheel = function() {
    var width = $( window ).width();
    if ( width > 954 ) {
        $( 'html' ).on( 'wheel', function( e ) {
            e.preventDefault();
            if ( Math.abs( e.originalEvent.deltaY ) >= Math.abs( e.originalEvent.deltaX ) ) {
                this.scrollLeft  = ( e.originalEvent.deltaY * 10 );
            } else {
                this.scrollLeft -= ( e.originalEvent.deltaX * 10 );
            }
        } );
    } else {
        $( 'html' ).off( 'wheel' );
    }
}
wheel();
$( window ).on( 'resize', wheel );

As you can see ( if (width > 954) ), the new behavior is just set on desktops, not mobile nor tablet devices. This is the vanilla JS code I came up with:

Vanilla JS:

var wheel = function() {
    var width = window.innerWidth;
    var scroll = function( e ) {
        e.preventDefault();
        if ( Math.abs( e.deltaY ) >= Math.abs( e.deltaX ) ) {
            this.scrollLeft  = ( e.deltaY * 10 );
        } else {
            this.scrollLeft -= ( e.deltaX * 10 );
        }
    } 
    if ( width > 954 ) {
        document.documentElement.addEventListener( 'wheel', scroll );
    } else {
        document.documentElement.removeEventListener( 'wheel', scroll );
    }
}
wheel();
window.addEventListener( 'resize', wheel );

But, when I resize the window to the tablet/mobile width, the horizontal scrolling is not disabled and I cannot scroll the site vertically. It seems as if the removeEventListener() function is not really removing my listener function.

Any ideas about what's going on here?

CodePudding user response:

You are binding wheel handler many times as you resize the window. I would suggest to bind it once and then check the window width in it. Maybe something like this:

var scroll = function( e ) {
    var width = window.innerWidth;
    if(width <= 954) return;
        
    e.preventDefault();
    if ( Math.abs( e.deltaY ) >= Math.abs( e.deltaX ) ) {
        this.scrollLeft  = ( e.deltaY * 10 );
    } else {
        this.scrollLeft -= ( e.deltaX * 10 );
    }
}

document.documentElement.addEventListener( 'wheel', scroll);
  • Related