Using pushState and replaceState
better linking
- tags
- javascript
Contents
window.history.pushState
and window.history.replaceState
make the back
button work right, and lets you share links to what you are looking at
if your page has form controls that set the state of things. Lets
look at how to use that.
Javascript
First we'll create a function that creates a state object based upon the url. This will return an object with all the key values that were passed in the url.
|
|
We can then write the reverse, which will change the location bar to
set values that are in the state object. If we pass in push = true
then in addition to changing the location bar it will also make the
back button keep another state.
|
|
Now lets handle initial load as well as the popstate
events for when a
user presses the back button. In this model of the page, each of the
url parameters that are passes coorespond to a DOM element.
|
|
Finally, lets add some events to our elements. For text inputs we are updating the value of the state and replacing the current URL, so linking works, and for the submit button we are pushing the state which will add an new history entry. This makes the back button work.
|
|
Boiler plate
|
|
To explore:
|
|
Previously
Next