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;
        });
    }
});
Était-ce utile?

La 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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top