Evanss
Evanss

Reputation: 23593

JavaScript function if url has hash tag and user has just navigated forward or back with browser?

The following will fire an alert when the page is refreshed if the hash tag ends in twoB:

if (window.location.href.match(/\#twoB/))
{
   alert('twoB');
}

The issue is that if you've clicked on a few hash tags and then click back in your browser, although the URL includes the hash the alert doesn't fire. How can I make the code fires (ideally only) after a user has gone back or forward with their browser.

I'm using jQuery for this project so i would like a jQuery solution in an ideal world if the syntax is easier.

Upvotes: 1

Views: 1783

Answers (3)

Domenic
Domenic

Reputation: 112837

$(window).on("hashchange", function () {
    console.log("hash is now " + window.location.hash);
});

Note that on was added in jQuery 1.7; if you're using an older version, then do $(window).bind instead.

Upvotes: 3

Jamie R Rytlewski
Jamie R Rytlewski

Reputation: 1221

Why don't you use location.hash instead of href.match? The location.hash should be faster as you are only getting the hash and you don't have to do a match?

Upvotes: 0

Evanss
Evanss

Reputation: 23593

Initially I solved this quite an ugly way of using setInterval to repeatedly check the URL. HTML5s onpopstate runs when the page is first loaded and then every forward and back navigation aswell.

window.onpopstate = function(){ 
  if (window.location.href.match(/\#twoB/))
  {
     alert('twoB');
  }
}

Upvotes: 0

Related Questions