How to manage the back button with JavaScript

Default avatar.
March 04, 2013
How to manage the back button with JavaScript.

ThumbnailOne 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:

var times = 0;
function doclick() {
document.getElementById('message').innerHTML =
'Recorded <b>' + times + '</b> clicks';

and a little markup:

<div onclick="doclick();">Click Me</div>
<div id="message">Recorded <b>0</b> clicks</div>

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.

  1. The user starts on their home page and decides to visit the amazing Click Me application they’ve heard about.
  2. They type in the URL or follow a link from an email to get to the Click Me page.
  3. After a few seconds of enjoyable interaction, the page state has changed several times.
  4. 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:

function doclick() {
location.hash = times;
document.getElementById('message').innerHTML =
'Recorded <b>' + times + '</b> clicks';
  1. The user arrives at the Click Me page as before.
  2. Notice that now the URL is updated after every click — ”#” has appeared at the end of it.
  3. 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:

function doclick() {
location.hash = times;
window.onhashchange = function() {
if (location.hash.length > 0) {
times = parseInt(location.hash.replace('#',''),10);
} else {
times = 0;
document.getElementById('message').innerHTML =
'Recorded <b>' + times + '</b> clicks';

The doclick() function is now only responsible for updating the times variable and changing the hash. The hashchange event is on the window object; when it takes place, you check that the hash exists. In a real application, you’d also want to check that it had a valid value. Next, you set the value of times to be the number in the hash. Finally, you update the document to reflect the correct page state. Let’s look at this new code:

  1. As before, the hash in the URL is updated as the user clicks.
  2. But now, when the Back button is clicked, the onhashchange function is triggered and the page state is reset to match the URL.

Using location.hash

The location.hash property and the associated hashchange event are useful if you want to tag particular views of your application and allow the user to navigate between them. Google Mail uses this approach by allowing you to navigate between your inbox (#inbox), contacts (#contacts), and other views — if you have a Gmail account, look at what happens to the URL as you navigate to various different pages and then click back.

But as far as state information goes, the hash only lets you store a string. You could encode a more complex object, but the URL would quickly become long and unwieldy and wouldn’t be memorable for your users. If you need more complex information stored as part of the history, a better approach would be to use the hash as a key to pull further state information out of some store. Although you could roll your own approach to this, HTML5 has provided an API to do it for you through the history.pushState() method and the popstate event. These methods allow you to save and reload a complex object.


You’ve learned that managing the browser’s history allows you make the Back button behave in a more sensible way in the context of your application, while the microdata API gives you access to structured semantic information in page contents.

What uses do you envisage for this technique? Have you developed a different method? Let us know in the comments.

Featured image/​thumbnail, go back image via Shutterstock.

Rob Crowther

Rob Crowther, Joe Lennon, Ash Blue and Greg Wanish’s HTML5 in Action is available in PDF, ePub, and Kindle from manning​.com/​c​r​o​w​t​her2/. The paperback will be released Nov 2013. Save 50% with Promo code wdcrowther2 until 1019. Offer valid only at manning​.com.

Read Next

15 Best New Fonts, May 2023

The choices you make when selecting a typeface have more impact on your design than almost any other decision, so it’s …

10+ Best Tools & Resources for Web Designers and Agencies (2023 updated)

Having the ability to envision a tastefully designed website (i.e., the role creativity plays) is important. But being …

20 Best New Websites, May 2023

This month, there are tons of great new agency websites to get excited about. 3D animated prisms are a popular theme, a…

How to Find the Right White Label Website Builder for Your Agency

Web design agencies face a lot of obstacles in closing the deal with new clients. One of the most common ones is the ar…

Exciting New Tools For Designers, May 2023

There are hundreds of new tools for designers and developers released each month. We sift through them all to bring you…

3 Essential Design Trends, May 2023

All three of the website design trends here mimic something bigger going on in the tech space, from a desire to have mo…

10 Best AI Tools for Web Designers (2023)

It’s time to stop worrying if AI is going to take your job and instead start using AI to expand the services you can of…

10 Best Marketing Agency Websites (Examples, Inspo, and Templates!)

Marketers are skilled in developing strategies, producing visual assets, writing text with high impact, and optimizing …

15 Best New Fonts, April 2023

Fonts are a designer’s best friend. They add personality to our designs and enable fine typography to elevate the quali…

20 Best New Websites, April 2023

In April’s edition, there’s a whole heap of large-scale, and even full-screen, video. Drone footage is back with a veng…

Exciting New Tools For Designers, April 2023

The AI revolution is having a huge impact on the types of products that are hitting the market, with almost every app b…

3 Essential Design Trends, March 2023

One thing that we often think about design trends is that they are probably good to make a list. That’s not always true…