Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting Back Button/Hash Change in URL

I just set up my new homepage at http://ritter.vg. I'm using jQuery, but very minimally.
It loads all the pages using AJAX - I have it set up to allow bookmarking by detecting the hash in the URL.

 //general functions  function getUrl(u) {       return u + '.html';  }  function loadURL(u)    {       $.get(getUrl(u), function(r){                 $('#main').html(r);            }       );  }  //allows bookmarking  var hash = new String(document.location).indexOf("#");  if(hash > 0)  {       page = new String(document.location).substring(hash + 1);       if(page.length > 1)         loadURL(page);       else         loadURL('news');  }  else       loadURL('news'); 

But I can't get the back and forward buttons to work.

Is there a way to detect when the back button has been pressed (or detect when the hash changes) without using a setInterval loop? When I tried those with .2 and 1 second timeouts, it pegged my CPU.

like image 473
Tom Ritter Avatar asked Oct 06 '08 01:10

Tom Ritter


1 Answers

The answers here are all quite old.

In the HTML5 world, you should the use onpopstate event.

window.onpopstate = function(event) {     alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); }; 

Or:

window.addEventListener('popstate', function(event) {     alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); }); 

The latter snippet allows multiple event handlers to exist, whereas the former will replace any existing handler which may cause hard-to-find bugs.

like image 155
Drew Noakes Avatar answered Sep 21 '22 02:09

Drew Noakes