Web Storage Example
by Sub Taper
HTML
<h1>Web Storage Example - Visit Counter</h1>
<div id="visitcounter"></div>
<label>Enter your name: </label>
<input type="text" id="name" /><br />
<button type="button" onclick="storeName();">Save/Update my name</button>
<p>Your total visit count is stored in your localStorage, you can inspect this using the Resources tab in Google's Chrome Developer Tools</p>
CSS
body {
font-family: sans-serif;
padding: 10px;
}
h1 {
font-weight: bold;
margin-bottom: 10px;
}
h3 {
margin-bottom: 10px;
}
input {
margin-top: 10px;
margin-bottom: 10px;
}
#visitcounter {
}
JavaScript
//Test for browser compatibility
if (typeof(Storage !== "undefined")) {
//check to see if the numvisits localstorage item is already set.
if (localStorage.getItem("numvisits")) {
//if it is, retrieve its value, increment it by 1 and update the value stored in the localstorage to reflect this.
var numvisits = parseInt(localStorage.getItem("numvisits"), 10) + 1;
localStorage.setItem("numvisits", numvisits);
//get the stored name, if one exists to be used in the welcome message
var welcomename = "";
if (localStorage.getItem("name")) {
var storedname = localStorage.getItem("name");
var welcomename = ", " + storedname;
document.getElementById("name").value = storedname;
}
//Update the visit counter item on the page with the number of visits the user has paid to the site
document.getElementById("visitcounter").innerHTML = "Welcome back" + welcomename + "! You have visited this page " + numvisits + " times.<br />";
} else {
//if numvisits was not already set, create it and set its value to 1
localStorage.setItem("numvisits", 1);
//Display an appropriate welcome message to the user for their first visit
document.getElementById("visitcounter").innerHTML = "Hello and welcome! I see you haven't visited here before..";
}
//get the updated numvisits localStorage item's value
var numvisits = localStorage.getItem("numvisits");
} else {
alert("Your Browser does not support the web storage APIs");
}
//store the user's name (as entered in the input field in the localStorage data store)
function storeName() {
//Get the name entered by the user
var newname = document.getElementById("name").value;
//Check if name already exists
if (localStorage.getItem("name")) {
//if the name is already stored, ask the user to confirm they wish to update it
var storedname =...