Only run the function once while scrolling (scrollstop)

So, I would like to run the function only once on the scroll (using the Scrollstop specified by stackoverflow answer)

The problem is that I do not run the function only once. I tried different solutions (.on (), setting the counter, setting it outside / inside the window.scrollstop function), but nothing worked.

I donโ€™t think itโ€™s difficult, but .. I couldnโ€™t get it to work so far.

Here is the plugin that I use

$.fn.scrollStopped = function(callback) { $(this).scroll(function(){ var self = this, $this = $(self); if ($this.data('scrollTimeout')) { clearTimeout($this.data('scrollTimeout')); } $this.data('scrollTimeout', setTimeout(callback,300,self)); }); }; 

and here is my code:

  $(window).scrollStopped(function(){ if ($(".drawing1").withinViewport()) { doNothing() } }) var doNothing = function() { $('#drawing1').lazylinepainter('paint'); } 

(deleted the counter since it did not work)

Live demo here

PS: the function that I would like to do only once is lazyPaint. It starts when we go to the element, but it fires again when it ends.

+8
source share
4 answers

how to use a variable to see if it was previously run:

 var fired = 0; $.fn.scrollStopped = function(callback) { $(this).scroll(function(){ if(fired == 0){ var self = this, $this = $(self); if ($this.data('scrollTimeout')) { clearTimeout($this.data('scrollTimeout')); } $this.data('scrollTimeout', setTimeout(callback,300,self)); fired = 1; } }); }; 
+7
source

Here, my version of the function fires once while listening to the scroll event:

 var fired = false; window.addEventListener("scroll", function(){ if (document.body.scrollTop >= 1000 && fired === false) { alert('This will happen only once'); fired = true; } }, true) 
+8
source

How about this solution?

 function scrollEvent() { var hT = $('#scroll-to').offset().top, hH = $('#scroll-to').outerHeight(), wH = $(window).height(), wS = $(this).scrollTop(); if (wS > (hT+hH-wH)){ console.log('H1 on the view!'); window.removeEventListener("scroll", scrollEvent); } } window.addEventListener("scroll", scrollEvent); 
0
source

Thanks @Henry Zhu for a great solution for vanilla js. Works great

-1
source

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


All Articles