Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop scroll() triggering events multiple times

Tags:

jquery

Im using jquery.visible.js to detect when a DIV is in view ( it starts the animation on plug in that has like a circle animation effect). But it keeps firing every time i use the scroll wheel, multiplying itself indefinitely and i cant find a way to stop it with off() or unbind()? thanks!

 // Check vertical for circliful using jquery.visible.js
$(window).scroll(function(){
    if ($("#moreSection").visible(true)){


        // trigger circliful
        $('#myStat-1').circliful() // this wont stop firing

}
});
like image 900
user3358014 Avatar asked Apr 15 '15 15:04

user3358014


People also ask

How often does scroll event fire?

The scroll event fires when the document view has been scrolled. For element scrolling, see Element: scroll event . Note: In iOS UIWebViews, scroll events are not fired while scrolling is taking place; they are only fired after the scrolling has completed. See Bootstrap issue #16202.

What method of the event object do you call to stop the scrolling behavior?

But we can prevent scrolling by event. preventDefault() on an event that causes the scroll, for instance keydown event for pageUp and pageDown . If we add an event handler to these events and event. preventDefault() in it, then the scroll won't start.

Does scroll event bubble?

The scroll event does not bubble up. Although the event does not bubble, browsers fire a scroll event on both document and window when the user scrolls the entire page.


2 Answers

as #Shikkediel pointed out scroll() gets fired on frame rate changes. so every scroll can trigger it hundreds of times.

you can do this:

$(window).scroll(function(){
    if ($("#moreSection").visible(true)){
        doActionAndStopScript();
    }
});

function doActionAndStopScript(){
    $('#myStat-1').circliful() // now it will fire once
    $(window).unbind('scroll');
}

you can only call the unbind() from outside the $(window)

like image 117
Aryeh Armon Avatar answered Sep 29 '22 02:09

Aryeh Armon


The scroll event will fire once for every pixel that is scrolled. To work around this behaviour you can use a timer which will only execute your logic after scrolling has stopped for x milliseconds. Try this:

var timer;
$(window).scroll(function() {
    clearTimeout(timer);
    timer = setTimeout(function() {
        if ($("#moreSection").visible(true)){
            $('#myStat-1').circliful();
        }
    }, 250);
});

250ms is normally long enough to wait to fire your code. You can tune this value as required.

like image 21
Rory McCrossan Avatar answered Sep 29 '22 00:09

Rory McCrossan