Lucas M
Lucas M

Reputation: 159

Disabling Mousewheel JS horizontal scroll under certain screen size

I'm using .mousewheel to translate my downwards scroll into horizontal scroll on desktop, however for mobile I want to disable this behavior. I have tried the following:

if ( $(window).width() > 480) {     
    $('html, body, *').mousewheel(function(e, delta) {
        this.scrollLeft -= (delta * -0.5);
        e.preventDefault();
    });
}
else {
    $("html, body, *").bind("mousewheel", function() {
        return false;
    });
}

But no success, the horizontal scrolling works fine but the body content is still locked in place on mobile.

Upvotes: 0

Views: 418

Answers (1)

Nerdwood
Nerdwood

Reputation: 4022

To get the viewport width:

var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)

Then you can just make a small change to your if statement:

if (viewportWidth > 480) { ... }

Full code example

This includes a little "fix-up" with the way that the scroll translation was happening - I couldn't get the previous way to work.

var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);

if (viewportWidth > 480) {
    $('body').mousewheel(function(e) {
        $(this).scrollLeft($(this).scrollLeft() - e.deltaY);
        e.preventDefault();
    });
} else {
    $("body").on("mousewheel", function() { return false; });
}

Upvotes: 1

Related Questions