Search code examples
javascriptjquerydelaywait

JavaScript / JQuery - How to temporarily disable function after use?


I have a simple JS that would smoothly autoscroll to another div whenever mousewheel is moved up or down.

Here's the script:

    $(document).bind('mousewheel', function(evt) {
        var delta = evt.originalEvent.wheelDelta
        if(delta < 0){
                $('html, body').animate({
                    scrollTop: $("#content-wrapper").offset().top
                }, 3000);
        }
        else {
                $('html, body').animate({
                scrollTop: $("#bgheader").offset().top
                }, 3000);
        }         
    });

My problem is that if i play for a few seconds with the mousewheel it would start scrolling here and there forever, since every move recorded is queued as additional script launch.

Is there any way to put some sort of 'cooldown' to the script? So that after using once it would become avaiable to use again in, let's say' 3 seconds? Or once the animation is finished?


Solution

  • You can unbind the wheel event listener, and then use jQuery's .animate() callback function to re attach the event listener after it is done, like so:

    function scrollHandler (event) {
        $(document).off("mousewheel.custom");
        var delta = event.originalEvent.wheelDelta
        if(delta < 0){
            $('html, body').animate({
                scrollTop: $("#content-wrapper").offset().top
            }, 3000, function () {
                // animation callback function
                $(document).on("mousewheel.custom", scrollHandler);
            }));
        }
        else {
            $('html, body').animate({
               scrollTop: $("#bgheader").offset().top
            }, 3000, function () {
              // animation callback function
              $(document).on("mousewheel.custom", scrollHandler);
            });
        }
    }
    
    // namespace the event so we can easily .off() it
    $(document).on('mousewheel.custom', scrollHandler);