Damian Doman
Damian Doman

Reputation: 532

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?

Upvotes: 0

Views: 449

Answers (2)

mhodges
mhodges

Reputation: 11116

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);

Upvotes: 1

Ogre Codes
Ogre Codes

Reputation: 19611

I've used timeouts.

var maxPoll = 3000,
    eventActive = false;

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

It's rough and it uses globals, but it basically turns off your event while the animation is running.

Upvotes: 0

Related Questions