Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a MouseWheel Event to fire only once in jQuery?

So I want to fire a function only once every time a user scrolls up or down via the Mousewheel. See: jsFiddle Demo. The issue is that even though I have the e.preventDefault(), the function still fires multiple times.

The goal is for the function to fire only once whenever a user scrolls up or down. Similar to this site.

Here is the code that I have so far:

var sq = {};
sq = document;
if (sq.addEventListener) {
    sq.addEventListener("mousewheel", MouseWheelHandler(), false);
    sq.addEventListener("DOMMouseScroll", MouseWheelHandler(), false);
} else {
    sq.attachEvent("onmousewheel", MouseWheelHandler());
}

function MouseWheelHandler() {
    return function (e) {
        var e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        if (delta < 0) {
            /* Scroll Down */
            e.preventDefault();
            console.log("Down. I want this to happen only once");

        } else {
            /* Scroll Up */
            console.log("up. I want this to happen only once");
            e.preventDefault();
        }
        return false;
    }
    return false;
}
like image 242
raeq Avatar asked Nov 27 '22 08:11

raeq


1 Answers

This has helped me:

var isMoving=false;

$(document).bind("mousewheel DOMMouseScroll MozMousePixelScroll", function(event, delta) {
   event.preventDefault();
   if (isMoving) return;
   navigateTo();
});

function navigateTo(){
   isMoving = true;
   setTimeout(function() {
    isMoving=false;
   },2000);
}

Basically you have a isMoving variable that is set depending on if your animation or whatever you do is in progress. Even though user scrolls multiple times with mousewheel in one "flick", the function fires only once.

like image 159
Darinka Kostelníková Avatar answered Nov 28 '22 23:11

Darinka Kostelníková