Changing the browser back button functionality

Keen Sage picture Keen Sage · May 5, 2013 · Viewed 10.1k times · Source

Use Case : I have a webpage which shows popovers for some of the functionalities. The popovers can be considered to be a HTML div which is shown when the corresponding button is clicked. And again go hidden when the cancel button is clicked / browser back button is clicked.

Problem : Consider that the popover is shown. When the user clicks the back button, he should not get navigated back to the previous page instead only the popover div should get hidden.

How do I add this functionality using javascript to the browser back button?

Thanks in advance

Answer

Matt Rohland picture Matt Rohland · May 5, 2013

It sounds like you're looking for the HTML5 History API.

A very good intro on how it works can be found at http://diveintohtml5.info/history.html .

Additional information can be found at http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html .

Also, you should look into polyfilling the feature for older browsers. There are plenty of options for doing so including https://github.com/browserstate/history.js , which includes some sample code and even a working demo (http://browserstate.github.io/history.js/demo/).