Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I prevent a custom event from being triggered repeatedly – or can I "reset" the jQuery .one() function?
    primarykey
    data
    text
    <p>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().</p> <p>The function to check if element is visible:</p> <pre><code>checkScrollPos = function() { if (objTopPos - scrollPos &lt;= windowHeight / 2) { $(document).trigger('objVisible'); } } </code></pre> <p>The function to listen for the event:</p> <pre><code>evtListener = function() { //startAnimation() should only be started once $(document).one( { 'objVisible': function(event) { startAnimation(); } } ); } </code></pre> <p>Here it all happens:</p> <pre><code>$(document).ready(function() { evtListener(); $(window).scroll(function () { scrollPos = $(document).scrollTop(); checkScrollPos(); } } </code></pre> <p>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 </p> <pre><code>$(document).one() </code></pre> <p>function – so that everytime the element gets out of sight, I can use the .one() function again. Is there any way to do that?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload