Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only fire a function once on scroll (scrollstop)

So, I'd like to fire a function only once on scroll (using Scrollstop, given by a stackoverflow answer)

The problem is that I don't get to fire the function only once. I've tried different solutions ( .on(), setting a counter, setting it outside/inside the window.scrollstop function) but nothing worked.

I don't think it's difficult, but.. I didn't get to make it work so far.

Here's the plugin I'm using

  $.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's my code:

        $(window).scrollStopped(function(){
            if ($(".drawing1").withinViewport()) {      
                doNothing()
                }
            })


var doNothing = function() {
            $('#drawing1').lazylinepainter('paint');
        }

(removed the counter since it didn't work)

Live demo here

PS: the function I'd like to make happen only once is the lazyPaint. It begins when we scroll to the element but it fires once again when it ends.

like image 221
Naemy Avatar asked Jun 01 '13 13:06

Naemy


People also ask

How often does scroll event fire?

Limit the minimum execution interval time of ONSCROLL event The onscroll event trigger interval time is around 10~20ms when we scrolling the mouse wheel.

Do scroll events 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

how about using a variable to see whether it was previously fired:

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;
              }
          });
      };
like image 83
AddiktedDesign Avatar answered Sep 19 '22 09:09

AddiktedDesign


Here's my version of having a function fire 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)
like image 28
Henry Zhu Avatar answered Sep 19 '22 09:09

Henry Zhu