简体   繁体   中英

Jquery trigger animation once on scroll

Trying to trigger an animation once on scroll, but it triggers multiple times.

$(window).scroll(function(){
  var y = $(window).scrollTop();
  var flagscroll=true;
  if( y < 30 && y > 20 && flagscroll==true ) {
        flagscroll=false;
       $('[data-label="SearchPanel"]').animate({ 
            top: "-=34px",
        }, 200 );
  }
});

What am I missing here? Thanks for your ideas!

Your flag is always set back to true for every scroll event. You must place the initialization outside of the event function declaration:

var flagscroll=true;

$(window).scroll(function(){
    var y = $(window).scrollTop();
    if( y < 30 && y > 20 && flagscroll==true ) {
        flagscroll=false;
        $('[data-label="SearchPanel"]').animate({ 
            top: "-=34px",
        }, 200 );
    }
});

set var flagscroll=true; before $(window).scroll

like

var flagscroll=true;
$(window).scroll(function(){
var y = $(window).scrollTop();
if( y < 30 && y > 20 && flagscroll==true ) {
    flagscroll=false;
   $('[data-label="SearchPanel"]').animate({ 
        top: "-=34px",
    }, 200 );
}
 });

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