简体   繁体   中英

How can I prevent a custom event from being triggered repeatedly – or can I “reset” the jQuery .one() function?

I have some code, that checks for the visibility of an element on the screen. As soon as it comes in sight by scrolling the page a custom event is triggered. This custom event starts an animation. To prevent this animation to be started over and over the function that starts it is only started once. For that I used the jQuery function .one().

The function to check if element is visible:

checkScrollPos = function() {
    if (objTopPos - scrollPos <= windowHeight / 2) {
        $(document).trigger('objVisible');
    }
}

The function to listen for the event:

evtListener = function() {
    //startAnimation() should only be started once
    $(document).one(
        {
            'objVisible': function(event) {
                startAnimation();
            }
        }
    );
}

Here it all happens:

$(document).ready(function() {
    evtListener();
    $(window).scroll(function () {
        scrollPos = $(document).scrollTop();
        checkScrollPos();
    }
}

Now this all works fine but I extended the checkScrollPos() function to also check if the element gets out of sight again, to then stop the animation. That works fine to. Problem is, as the events trigger, the event-bound functions only are executed one time. So when you scroll teh element in sight, then out of sight and then in sight again the animation will not be executed again (what is the correct behaviour of course). Now I would like to have it that the events are triggered exactly one time but EVERYTIME the element gets in or out of sight and not just one time at all. So basicly I need some kind of reset for the

$(document).one()

function – so that everytime the element gets out of sight, I can use the .one() function again. Is there any way to do that?

You have to bind the objVisible event every time the element disappears.

Just call evtListener() after the element is out of sight, so that the objVisible event is bound again.

Your code would be something like this:

checkScrollPos = function() {
    if (objTopPos - scrollPos <= windowHeight / 2) {
        $(document).trigger('objVisible');
    }

    if (/* your condition to check if element is out of sight */) {
        evtListener();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM