Question

I'm using the jquery-mousewheel plugin to trigger a function.

When I call moveit I detach the listener and wait until the animation is completed, then I re-attach the listener.

The problem is that when I re-attach it, the mousewheel plugin is still listening to the inertia of some mouses/trackpads, and call moveit repeatedly.

I guess debouncing or throttling the function call are not good solutions in my specific case, because the inertia is still there, and I also want the listener to be attached immediately for other possible moveit calls.

Is there a way to "kill the inertia" by completely resetting the mousewheel event, instead of only detaching it?

$(document).ready(function () {

    var tween;
    var slide = $('#slide');

    function bodyListen () {
        $('body').on('mousewheel.bodyscroll',
        function (e, delta, deltaX, deltaY) {
            e.preventDefault();
            $('body').off('mousewheel.bodyscroll');
            moveit();
        });
    }

    function moveit () {
        tween = TweenMax.to(slide, 0.8, {
            marginLeft: 300,
            onComplete: bodyListen
        });
    }

    bodyListen();
});
Was it helpful?

Solution

Use flags when dealing with events (or any manipulation related to the DOM), beacuse event listener can often behave like asyncronous functions.

$(document).ready(function () {

    var tween;
    var slide = $('#slide');
    var flag = true;

    function bodyListen () {
        $('body').on('mousewheel.bodyscroll',
        function (e, delta, deltaX, deltaY) {
            if(flag){
                e.preventDefault();
                flag = false;
                moveit();
            }
        });
    }

    function moveit () {
        tween = TweenMax.to(slide, 0.8, {
            marginLeft: 300,
            onComplete: function(){
                flag = true;
            }
        });
    }

    bodyListen();
});

OTHER TIPS

Although I have not tried this myself, TweenMax has Kill Tweens of and KillAll that allow you to kill a tween and optionally complete them before you do. maybe not what you want, because it would force the animation to finish but it gets you back to a state you want and the code insert is simple. At the beginning of function bodyListen

function bodyListen() {
    if(tween) tween.killAll(true)
    .....
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top