How to determine if an item has been scrolled, but only once?

I am trying to detect if an element has been scrolled and made the following code

$(window).bind('scroll', function(){
    var $btn = $('#intro div.summary a[href=#top]');
    if($(window).scrollTop() > ($btn.offset().top+$btn.height())){
        console.log('out');
    }
});

I have an anchor in some body text that I hope to clone and make fixed navigation after div.intro scrolls.

My problem is that the code fires as soon as the element leaves the field of view, but continues to shoot. Therefore, I can’t do it anymore, as it will shoot more and more.

Is there any way to shoot β€œout” after it comes out and β€œin” after turning it on? Besides just setting a variable.

+3
source share
2 answers

To execute an event only once, you can do

$(window).one('scroll', function(){
    var $btn = $('#intro div.summary a[href=#top]');
    if($(window).scrollTop() > ($btn.offset().top+$btn.height())) {
        console.log('out');
    }
});
+7
source

, unbind :

$(window).bind('scroll', function(){
    var $btn = $('#intro div.summary a[href=#top]');
    if($(window).scrollTop() > ($btn.offset().top+$btn.height())) {
        console.log('out');
        $(window).unbind('scroll');
    }
});
+1

Source: https://habr.com/ru/post/1792882/


All Articles