One major issue with JavaScript-based applications is that they break the Back button. If you update content on the page with JavaScript rather than loading a new page from the server, no entry made is in the browser history; so when the user clicks Back, expecting to go back to the previous state, they end up at the previous site instead.
Drag and drop is a great way for users to interact with your web applications. But the usability gains will be lost if, after spending time moving through your application, users click the Back button expecting to go back a page and instead go back to their Start screen. In this article “Hello! HTML5 & CSS3″ author Rob Crowther shows you how to use the HTML5 history API to avoid that fate.
The problem can be demonstrated simply. All you need is a function that updates the page in response to user activity:
In real life, your web page would be doing something more complicated, like fetching new content from the server via AJAX, but a simple update is enough to demonstrate the concept. Let’s see what happens when the user visits the page.
- The user starts on their home page and decides to visit the amazing Click Me application they’ve heard about.
- They type in the URL or follow a link from an email to get to the Click Me page.
- After a few seconds of enjoyable interaction, the page state has changed several times.
- But when the user clicks the Back button in the browser, they find that instead of going back to a previous page state, they leap to their home page.
The doclick() function can be updated to take advantage of the history API. Each time the page is updated it will also set the location.hash:
- The user arrives at the Click Me page as before.
- Notice that now the URL is updated after every click—”#” has appeared at the end of it.
- Clicking the Back button now takes the location back to #2, demonstrating that page states have successfully been added to the history. But note that clicking the Back button doesn’t automatically return the page to its previous state.
Updating page state
Updating the history is only part of the problem; you also need to be able to update the state of the page to match the state in the history.
Because you’re the one managing the history, it’s up to you to manage the page state. In order to update your page in response to location.hash being changed, you can listen to the hashchange event:
