Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(window).scroll() firing on page load

Is there a way to prevent $(window).scroll() from firing on page load?

Testing the following code in Firefox 4, it fires even when I unplug the mouse.

jQuery(document).ready(function($){    
$(window).scroll(function(){
                console.log("Scroll Fired");
    });
});
like image 588
Mild Fuzz Avatar asked Jun 23 '11 10:06

Mild Fuzz


1 Answers

The scroll event is unrelated to the mouse, it is called whenever a new document scrolling position is set. And arguably that position is set when the document loads (you might load it with an anchor after all), also if the user presses a cursor key on his keyboard. I don't know why you need to ignore the initial scroll event but I guess that you only want to do it if pageYOffset is zero. That's easy:

var oldPageYOffset = 0;
$(window).scroll(function(){
  if (window.pageYOffset != oldPageYOffset)
  {
    oldPageYOffset = window.pageYOffset;
    console.log("Window scrolling changed");
  }
});

Note: MSIE doesn't have window.pageYOffset property so the above will need to be adjusted. Maybe jQuery offers a cross-browser alternative.

like image 60
Wladimir Palant Avatar answered Sep 28 '22 00:09

Wladimir Palant