Detach and re-attach mousewheel event listener don't reset scroll inertia
Asked Answered
G

2

7

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();
});
Gel answered 27/9, 2013 at 1:46 Comment(3)
Did you get anywhere with this?Ba
@dazhall unfortunately i had to adopt a workaround, like everybody do. i simply delayed the re-attachment of the mousewheel listener :(Gel
Why don't just add a global flag instead of detaching the event listener? If the flag is on, the listener do nothing, else does what it have to.Hardigg
H
5

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();
});
Hardigg answered 14/2, 2014 at 10:16 Comment(0)
J
0

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)
    .....
Jane answered 12/2, 2014 at 15:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.