javascriptjquery

On Scroll fires automatically on page refresh


Im halfway down my page as I have an anchor. I also have a window scroll event:

$(window).scroll(function(){
});

When I refresh the page, the scroll event fires. Is there a way to prevent this on the refresh but still listen for the scroll event when the user scrolls?


Solution

  • You can use a flag variable to detect whether the scroll event is the initial scroll event or not, effectively stopping the callback function's execution for the scroll event on page reload.

    var initialScrollEvent = true;
    
    $(window).scroll(function() {
      if (!initialScrollEvent) {
        // callback function body
      }
      initialScrollEvent = false;
    });