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?
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?
Share Improve this question edited May 21, 2013 at 5:48 Andrew Marshall 97.1k20 gold badges227 silver badges217 bronze badges asked Dec 18, 2011 at 23:25 RichardRichard 4,4157 gold badges38 silver badges58 bronze badges 3- 1 Why reinvent the wheel? History.js does this all quite well and includes HTML5's pushState. – Andrew Marshall Commented Dec 18, 2011 at 23:28
- Hi Guys, thanks! Andrew's tip about history.js suited my needs perfectly! Andrew; if you can add your ment as answer I can accept it.. – Richard Commented Dec 21, 2011 at 18:51
-
thanks, just made an answer
:)
. – Andrew Marshall Commented Dec 21, 2011 at 19:00
3 Answers
Reset to default 4Why 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).
Take a look at the hashchange
event. It fires when the hash is changed. However, you should only do this for Internet Explorer 8 support.
Internet Explorer 7 does not support hashchange
, so you can't rely on that. As for Internet Explorer 9, it (along with Chrome, Safari and Firefox, of course) supports the History API, which you should be using instead. It keeps your URLs clear, short and semantic, while enabling elegant Back/Forward button support.
There is a jQuery-Plugin that seems to be doing exactly what you want.
http://www.asual./jquery/address/
It was the highest voted answer for the questing What is the best back button jQuery plugin?