HTML and CSS Reference
In-Depth Information
Now let's look at the implementation.
A. DECLARE A VARIABLE TO HOLD THE STATE
You start by declaring a global variable to hold your state:
var state;
B. CREATE THE INITIAL STATE
Now you need to set initial values of your state object. For this exam-
ple, you need a property to hold a reference you can use in the hash,
and the content of your editable region:
function init() {
state = {
undonum: 0,
content: document.getElementById('content').innerHTML
};
}
C. SAVE THE STATE WITH PUSHSTATE
When the user saves, that state needs to be updated and then pushed
into the history object:
function save() {
state.undonum++;
state.content = document.getElementById('content').innerHTML;
history.pushState(state, '', '#undo' + state.undonum);
}
The pushState function takes three parameters: the object to be stored
as the state, a title for the state, and a hash to reference the state. Note
that the title is advisory only; currently most browsers ignore it. The
hash will be updated automatically by calling pushState .
D. WRITE A FUNCTION FOR THE POPSTATE EVENT
You also need a function to restore the state: it will be an event handler
for the popState event. The state object is available on the event passed
in, so you grab that and update the page from the content property:
function popState(event) {
if (event.state) {
Search WWH ::




Custom Search