Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle browser back button with Javascript / different approach possible by using anchors?

I'm currently struggling with a good navigation on a website using Ajax calls and unobstrusive JS. I'm catching the click event on links, load the content, attach it to a div and then return false. This works quite well and also allows Google to crawl the site with speaky URLs.

But I didn't know how to deal with the browser back button. I found this solution to catch the event when the user clicks on the back button:

http://www.bajb.net/2010/02/browser-back-button-detection/

It works quite well. But I also want the back button to work normally when the user found the website via a link and wants to return to the previous page (I don't want to trap anyone).

When I thought about it the best way would be to use anchors. The normal back button supports them and you can go back in history without reloading the page (/#1 <- /#2 <- /#3 etc.)

It would work like this:

  • Use normal URLs in the link, but catch the click event
  • When user clicks, load content and attach it to a DIV
  • Change the window.location, using an anchor (e.g. 'domain.com/#products/women-clothing' with window.location="#products/women-clothing";)
  • When the window.location changes, get the anchor, read out the path and get the content via ajax, attach it to a DIV

Only the last part isn't really clear for me and I could need help here.

Finaly, my question: Does this make any sense?

Thanks!

like image 485
Ole Spaarmann Avatar asked Jun 16 '26 17:06

Ole Spaarmann


1 Answers

Just add the href to window.location.hash after loading the content into a div. Then you can use that back button detection script to load what ever is in the hash.

like image 91
Marcel Avatar answered Jun 18 '26 08:06

Marcel