Listing 3: Showing the Theme Page 2
<!DOCTYPE html> <br>
<html><head><br>
<meta charset="UTF-8" /><br>
<title>11.3 Showing the Theme - Page 2</title><br>
<style><br>
#themeContent {<br>
background-color:#FFF;<br>
border-style:solid;<br>
border-width:2px;<br>
}<br>
#themeSettings {<br>
margin:10px;<br>
}<br>
</style><br>
<script><br>
<br>
// initialize our page<br>
function init() {<br>
<br>
// retrieve the saved theme color<br>
var themeColor = sessionStorage.getItem('themeColor');<br>
applyTheme(themeColor);<br>
}<br>
<br>
// apply the theme to the page<br>
function applyTheme(themeColor) {<br>
<br>
document.body.style.backgroundColor = themeColor;<br>
<br>
var themeDiv = document.getElementById('theme');<br>
themeDiv.innerHTML = themeColor + ' theme.';<br>
<br>
}<br>
<br>
// initialize the page<br>
window.addEventListener('load',init,false);<br>
<br>
</script><br>
</head><br>
<body><br>
<div id="themeContent"><br>
<div id="themeSettings"><br>
<H1>Page 2</H1><br>
<div id="theme"></div><br>
<br><br><br>
<a href="11_2_theme_page_1.html">Go To Page 1</a><br>
</div><br>
</div><br>
</body> <br>
</html>
When page 1 is loaded into your browser, the page first retrieves the currently stored theme color from the session storage. The first time the page is run, there is no theme, and the return value is empty, so the theme is set to the browser's default. On subsequent loads of the page, the color would be retrieved, set to the background color, and set as the selected value in the color select control.
Note: To run recipes involving session storage, you will need to upload the pages to a server instead of running them in local mode. The reason is that in local mode some browsers will throw an error saying that the operation is not supported. For example, in Firefox, an Operation is not supported code 9 error will be thrown.
Once loaded, the visitor can change the drop-down list of options to another color, which will change the page background color and store the color in session storage under the key themeColor. In the script, this setItem call to store the setting has been wrapped in a try-catch block. If triggered because of the size constraints, the code informs the visitor that the session storage is full, but you could perform whatever actions are needed when this scenario occurs.
After setting the theme color, the visitor can click Go To Page 2, which will load the second page. Since the second page is in the same session as the first page, it will also have access to the session storage key/value pair saved on page 1. The second page then retrieves this item and sets the background to the stored color.
In Listing 2, you also added the option for the visitor to reset the theme. In this case, the recipe removes the key/value pair from the session storage with the removeItem method. The recipe could have also updated the key by calling setItem with an empty string value.
At the beginning of this article, we discussed how session storage allows you to store data for that session only. If you load the page created in Listing 2 into two tabs or windows in the same browser and then select different colors, each tab will have its own background color since there is a different session for each tab or window. To have the values available across browser windows or tabs, and even after the browser is closed and reopened, you will need to use the local storage object. We will look at the local storage object in the next recipe.
Intermediate recipe: Storing forms with local storage
Session storage, as shown in the previous recipes, provides you with a method to store items for the period of the visitor's session, which can be beneficial for short-term storage. At times, though, you will want to store data in the visitor's browser for use when they return or even across currently active sessions. This is where local storage is valuable. Local storage uses the same key/value pair list to store data with the getItem, setItem, and removeItem web storage methods. The important factor is that the data you store in local storage persists even after the session is closed.
This recipe shows an example of remembering form data that a visitor has previously filled out. A visitor could come to your site, start a form, and then navigate away or close their browser. Typically, the visitor would have found the form empty when they returned to the site.
In this recipe, as the visitor fills out the form, the JavaScript catches the changes and stores the form fields and values in the local storage. Then if the page is closed and reloaded, the page checks local storage to see whether there is stored form data and automatically populates the form with the information. A similar implementation could even handle collecting form data from a multipage form and storing it locally until the entire form has been completed.
Two new concepts with the session and local storage are employed in this recipe: key and length. The key method allows you to retrieve the name of the key stored by sup-plying an index value to the key method:
DOMString key(index)
Here, index is the index of the key/value pair to return the key string for. The recipe also uses the length property of the session and local storage, which returns the number of key/value pairs in the session or local storage. To return the number of key/value pairs, you would use a call like the following:
var numItems = localStorage.length;
In this recipe, you will use both the key method and the length property to loop through the localStorage key/value pairs. Let's do the following steps to get started with Listing 4:
- Create a blank HTML file and add the body HTML from Listing 4, which holds the form and form fields you will be using. For simplicity sake, we have used on-change inline for the form fields, but you could replace these with event listeners for each of the fields.
- Add the script tags in the head of the HTML file with the window
- .addEventListener function to launch the checkStorage function when the page is loaded.
- Add the checkStorage function in the script, as shown in Listing 4.
- Add the changeField function in the script, as shown in Listing 4, which will handle the form field changes.
- Load the file in your Chrome browser with the Developer Tools open to the local storage area, and enter information in the fields.