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() {
times++;
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() {
times++;
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() {
times++;
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.

Summary

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/crowther2/. The paperback will be released Nov 2013. Save 50% with Promo code wdcrowther2 until 10/19. Offer valid only at manning.com.

Popular Posts

Read Next

Exciting New Tools for Designers, November 2023

We’ve got a mix of handy image helpers, useful design assets, and clever productivity tools, amongst other treats. Some…

The Dangers of Doomscrolling for Designers and How to Break Free

As a creative professional, navigating the digital realm is second nature to you. It’s normal to follow an endless…

From Image Adjustments to AI: Photoshop Through the Years

Remember when Merriam-Webster added Photoshop to the dictionary back in 2008? Want to learn how AI is changing design…

3 Essential Design Trends, November 2023

In the season of giving thanks, we often think of comfort and tradition. These are common themes with each of our three…

30 Obsolete Technologies that will Perplex Post-2000s Kids

Remember the screech of dial-up internet? Hold fond memories of arcade machines? In this list, we’re condensing down 30…

15 Best New Fonts, October 2023

We’re entering the final quarter of 2023, and even in the pre-holiday lull, there are still plenty of fonts to get…

Progressive Web Apps (PWAs): Unlocking The Future of Mobile-First Web Development

There are over 5.4 billion mobile users today, meaning that over 68% of the population tap into an online business via…

The 12 Most Controversial Ad Campaigns of the 21st Century

How far would an organization be willing to go for the chance to generate a little extra buzz? In this list, we're…

20 Best New Websites, October 2023

The Bento trend is still going strong: In some cases, we see this extend to the layout, but many more are picking…

Exciting New Tools for Designers, October 2023

This month, we have a whole bag of goodies for designers, developers, and designevelopers alike. (Yes, we did just make…

The 10 Most Successful Rebrands of All Time - Ranked

We’re all familiar with rebrands going wrong, but what happens when they go right? From McDonald’s health kick to…

3 Essential Design Trends, October 2023

Every now and then, website design trends can leave you scratching your head. This month’s collection includes some of…