panthro
panthro

Reputation: 24061

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?

Upvotes: 0

Views: 3681

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92274

I believe your scroll code only fires if you refresh the page and the page is scrolled. That's because the browser will reload the page, and then scroll to the original position.

The solution suggested by Arnelle does not work well, because the scroll event only fires initially if the page was scrolled when you refreshed it.

Hack Alert

What I found that does work is waiting to set the scroll handler. Be careful, I'm using magic numbers that may not work on all connections.

//Scroll the page and then reload just the iframe (right click, reload frame)


//Timeout of 1 was not reliable, 10 seemed to be where I tested it, but again, this is not very elegant.
//This will not fire initially
setTimeout(function(){
  $(window).scroll(function(){
     console.log('delayed scroll handler');
  }); 
}, 10); 

//This will fire initially when reloading the page and re-establishing the scroll position
$(window).scroll(function(){
  console.log('regular scroll handler');
});
div {  
  height: 2000px;
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>

And yes, I know I bashed Arnelle by saying they patched a problem without understanding, and here I am, suggesting a patch. The only difference is that I think I understand the problem.

My main question to the OP is. Most scroll handlers that I've written work fine if called multiple times, what is the problem with your handler being called an extra time?

Upvotes: 4

Arnelle Balane
Arnelle Balane

Reputation: 5487

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;
});

Upvotes: 2

Related Questions