Run jQuery event only once after condition is met

I make an online product site, I fire a scroll event, only 12 elements will be shown at launch, but when the eighth element scrolls to the top scroll, it should only fire once, but it fires every time I scroll down, please help. Here is my code:

var navigation_offset_top = $('.prods-list li:nth-child(4)').offset().top; $(window).on("scroll",function(){ var scroll_top = $(window).scrollTop(); // current vertical position from the top // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative if (scroll_top > sticky_navigation_offset_top) { console.log("Hi"); } }); 
+4
source share
5 answers

Use on() and off() and untie the event handler when the scroll reaches the correct point:

 var navigation_offset_top = $('.prods-list li:nth-child(4)').offset().top; $(window).on("scroll", doScroll); function doScroll() { var scroll_top = $(window).scrollTop(); if (scroll_top > sticky_navigation_offset_top) { console.log("Hi"); $(window).off('scroll', doScroll); } }); 
+4
source

I think you need a .one method

 $(window).one("scroll",function(){ var scroll_top = $(window).scrollTop(); // current vertical position from the top // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative if (scroll_top > sticky_navigation_offset_top) { console.log("Hi"); } }); 

You can find out more here: http://api.jquery.com/one/

+4
source

Call unbind() to untie the event from the object.

 $(window).on("scroll",function(){ var scroll_top = $(window).scrollTop(); // current vertical position from the top // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative if (scroll_top > sticky_navigation_offset_top) { console.log("Hi"); } $(this).unbind("scroll"); }); 
+3
source

You can cancel the event after completion.

Like $(this).unbind("scroll);

0
source
 var thisHash = window.location.hash; jQuery(document).ready(function() { if(window.location.hash) { jQuery.fancybox(thisHash, { padding: 20 // more API options }); } }); 

This is even better because you do not need a button to launch fancybox. And with the previous code, I could not insert the form inside fancybox, because every time I clicked inside the form, it restarted fancybox.

-1
source

All Articles