Search code examples
javascriptjqueryajaxhashbang

Catch "Back" event in browser and load different content


I've been working on a project using the hashbang (#!) method to skip though pages. Basically there is only 1 page, and when you click to go to a diffrent page, you stay on the page, but the URL changes, e.g. from index.html#home to index.html#about and new content is loaded via AJAX/JSON. All works well, but if I go "back" (or forward) in the browser, only the page in the URL changes, but my jQuery isn't fired to reload the content.

What I need is some code that will handle both the back and forward actions in all browsers, so that I can fire the function to load the page from jQuery. How do I do this?


Solution

  • Why reinvent the wheel? History.js is a great & well-maintained jQuery plugin that supports the new HTML5 History API and falls back gracefully to using hash URLs instead when the History API isn't supported. Works in just about every browser (even IE 6).