anthony-dandrea
anthony-dandrea

Reputation: 2813

How to run a function on load, back, and forward

I've looked at a few other dated questions on this site and have found their solutions don't seem to work on modern browsers anymore.

var foo = function() {
  console.log('woohoo');
};
foo();

I want this to run everytime. I obviously have no problem running it on the first initial load but I am using url hashes to hide and show certain divs of content. When a user clicks forward and backward I would like this function to run again as well.

Upvotes: 0

Views: 88

Answers (1)

Russell Durham
Russell Durham

Reputation: 624

Browsers cache the page so that they load faster on back/forward. For this reason the load events are never fired and that would also be why your code isn't run again. The browser is just restoring a previous state.

See this answer for more details on this.

Since you are just dealing with hashes you could try binding to the onhashchange event and calling your method then.

window.addEventListener("hashchange", foo);

If you're using a single page framework such as Angular, Backbone or one of the many others they usually provide you with a way to handle this as well so check the documentation if that's the case.

Upvotes: 3

Related Questions