Question

I have a function that prevents the default behavior of mouse wheel and it makes it scroll horizontally, but the problem is that when the window width is smaller than 970px the default behave doesn't work even though i use return true;

Code:

$(window).resize(function() {
    if($(window).width() >= 970) {
        $('.swiper-container').bind('mousewheel', function(event, delta) {
            this.scrollLeft -= (delta * event.deltaFactor);
            event.preventDefault();
        });
    } else {
        $('.swiper-container').bind('mousewheel', function(event, delta) {
            this.scrollTop -= (delta * event.deltaFactor);
            return true;
        });
    }
});
Was it helpful?

Solution

The problem is that bind adds an event listener, and not replace it. So you are adding several listeners each time you resize. Instead, you could just check the width inside it.

$('.swiper-container').on('mousewheel', function(event, delta) {
    if($(window).width() >= 970) {
        this.scrollLeft -= (delta * event.deltaFactor);
        event.preventDefault();
    } else {
        this.scrollTop -= (delta * event.deltaFactor);
    }
});

Also, use on instead of bind. You also don't need the else part if what you want is the default behaviour.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top