Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to browser history without page reload

Tags:

Basically, I have a page that contains a form. When a user submits that form, a Javscript function is called and the user is dynamically presented with a new form.

At this point, what I would like is for the user to be able to click the browser's back button and be taken back to the first form. Is this possible?


Thanks for the quick responses, but I am having trouble getting pushState to work. The HTML still displays "second form" after I click the back button.

Here is the code I used to test it:

<script> function newPage(){     history.pushState({state:1}, "State 1", "?state=1");     document.getElementById('formBox').innerHTML="second form"; } </script>   <input type="button" onclick="newPage();" value="forward" /> <div id='formBox'>first form</div> 
like image 866
twiz Avatar asked May 10 '12 20:05

twiz


People also ask

How do I change a page without reloading?

Method 2: Adding a new state with pushState() Method: The pushState() method is used to add a new history entry with the properties passed as parameters. This will change the current URL to the new state given without reloading the page.

What is JavaScript history?

JavaScript was invented by Brendan Eich in 1995. It was developed for Netscape 2, and became the ECMA-262 standard in 1997. After Netscape handed JavaScript over to ECMA, the Mozilla foundation continued to develop JavaScript for the Firefox browser.


2 Answers

var stateObj = { foo: "bar" }; history.pushState(stateObj, "page 2", "bar.html"); 

Relevant link to the docs.

like image 178
Elliot Bonneville Avatar answered Jan 03 '23 15:01

Elliot Bonneville


I've accomplished similar behaviour with the HTML5 History/State APIs, using History.js, described thus:

Provide a cross-compatible experience for all HTML5 Browsers (they all implement the HTML5 History API a little bit differently causing different behaviours and sometimes bugs - History.js fixes this ensuring the experience is as expected / the same / great throughout the HTML5 browsers)

Example:

History.pushState({state:1}, "State 1", "?state=1"); 
like image 22
Michael Robinson Avatar answered Jan 03 '23 14:01

Michael Robinson