• About Us
    • New York
  • Work
  • Capabilities
  • Careers
  • Technology
  • Blog
  • Contact Us
  • About Us
    • New York
  • Work
  • Capabilities
  • Careers
  • Technology
  • Blog
  • Contact Us
April 19, 2012

Using HTML5’s LocalStorage Like A Boss

Posted by Chris Alvares

The problem with using web browser cookies is they are passed from server to browser back to server, and while this is good way to send relevant persistent data to the server, it isn’t good for stuff like saving input field values, especially if those values can change depending on the type of page you are on, you are going to end up with a ton of useless data being passed with every request. W3C took to try to solve this problem. The first attempt by the W3C and the browser makers tried to implement was a SQLite type database. They called the original specification WebDB. However, after its inception, the developers at Mozilla did not want to implement it. They complained, saying that developers do not want to use SQL in the browser (You can read the conversation here). When I first read about this, I was shocked, and thought that Mozilla developers were just being lazy. That changed when I first started using HTML5’s new LocalStorage feature. It is exactly what the web needed. No longer tied down from having to have SQL queries, the key-value storage engine was perfect for 99% of web applications. Here is one way to use LocalStorage like a boss.

In this example, we will be creating two javascript methods to turn any pages input fields to automatically fill in previous values when the user hits the “Submit” button.

HTML Shell

Lets start out with a basic HTML Shell, and also include jQuery into the mix to make things move a bit faster.


<!DOCTYPE html>

<html>

<head>

<title>Local Storage Like a Boss</title>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

</head>

<body>

<form>

<table>

<tr>First Name: </tr><td><input type="text" name="fname" id="fname"></input></td>

<tr>Last Name: </tr><td><input type="text" name="lname" id="lname"></input></td>

<tr><td colspan="2" style="text-align:right"><button onclick="saveToLocalStorage(); return false;">Save</button></td></tr>

</table>

</form>

</body>

</html>

Save to Local Storage

As you can see from the HTML shell we built, the <button> has an onclick event titled saveToLocalStorage().


function saveToLocalStorage()

{

if(window.localStorage != null)

{

//use the URL of the page as our "key"

var url = location.href;

if(url.indexOf("#") != -1)

url = url.substr(0,url.indexOf('#'));

var key = "inputs-" + url;

var values = {};

jQuery("form input").each(function(){

values[jQuery(this).attr("name")] = jQuery(this).val();

});

try

{

localStorage.setItem(key, JSON.stringify(values));

}

catch(e)

{

localStorage.removeItem(key);

}

}

}

 

Lets walk this line by line.

The first thing we need to do is check if LocalStorage is supported, and the way we do that is with the line:


if(window.localStorage != null) {

This will make all browsers that do not support it act in a normal behavior. The next thing we have to do is creating a key value pair for our input fields. Now, there are two ways to do this, use seperate key values pairs for each input field, or, the way I like to do it, have one key-value pair where they key is the URL of the webpage, and the value is a JSON string with each of the key value pairs. This makes it faster to retrieve key value pairs from LocalStorage, and it is easy to iterate through the JSON data to fill in all the input fields.


//use the URL of the page as our "key"

var url = location.href;

if(url.indexOf("#") != -1)

url = url.substr(0,url.indexOf('#'));

var key = "inputs-" + url;

//use a dictionary as the keys

var values = {};

//get all of the input fields on the page, and call them by their names, if they have a name

jQuery("form input").each(function(){

if(jQuery(this).attr("name") != "")

values[jQuery(this).attr("name")] = jQuery(this).val();

});

Finally, the LocalStorage part comes. To store something in the LocalStorage, it is as easy as calling the window.localStorage class and the setItem method.


try

{

localStorage.setItem(key, JSON.stringify(values));

}

catch(e)

{

localStorage.removeItem(key);

}

Notice how I have a try and catch method around the setItem method. This is because the browser limits the LocalStorage of your domain to a certain amount. Most browsers have a default 5-10MB, so we should be ok in this situation, but it isn’t bad to remove the items if the LocalStorage does get too big.

Setting Variables From Location Storage


jQuery(document).ready(getFromLocationStorage);

function getFromLocationStorage()

{

if(window.localStorage != null)

{

//use the same URL as our key

var url = location.href;

if(url.indexOf("#") != -1)

url = url.substr(0,url.indexOf('#'));

var key = "inputs-" + url;

try

{

var values = JSON.parse(localStorage.getItem(key));

for(var index in values)

{

jQuery("form input[name=" + index + "]").val(values[index]);

}

}

catch(e)

{

//it is entirely possible that there is nothing in the item

}

}

}

The first thing we do is use jQuery’s ready event to load in all of the input fields with the data from LocalStorage


jQuery(document).ready(getFromLocationStorage);

Our getFromLocationStorage method starts out very similar to our saveToLocalStorage method, we get the currentURL that we used as our key.


//use the same URL as our key

var url = location.href;

if(url.indexOf("#") != -1)

url = url.substr(0,url.indexOf('#'));

var key = "inputs-" + url;

I wish this blog post would be more complicated, but LocalStorage is so easy to use. It is super simple, to get our items from the localStorage, we just call LocalStorage’s getItem method.


try

{

var values = JSON.parse(localStorage.getItem(key));

for(var index in values)

{

jQuery("form input[name=" + index + "]").val(values[index]);

}

}

catch(e)

{

//it is entirely possible that there is nothing in the item

}

We then set the values of input field from the JSON data we received from the LocalStorage. That is it; seemless and simple. I can now see how Mozilla was hesitant to implement a SQLite database in its browser.

Here is the code in full.


<!DOCTYPE html

><html>

<head>

<title>Local Storage Like a Boss</title>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">

jQuery(document).ready(getFromLocationStorage);

function getFromLocationStorage()

{

if(window.localStorage != null)

{

//use the same URL as our key

var url = location.href;

if(url.indexOf("#") != -1)

url = url.substr(0,url.indexOf('#'));

var key = "inputs-" + url;

try

{

var values = JSON.parse(localStorage.getItem(key));

for(var index in values)

{

jQuery("form input[name=" + index + "]").val(values[index]);

}

}

catch(e)

{

//it is entirely possible that there is nothing in the item

}

}

}

function saveToLocalStorage()

{

if(window.localStorage != null)

{

//use the URL of the page as our "key"

var url = location.href;

if(url.indexOf("#") != -1)

url = url.substr(0,url.indexOf('#'));

var key = "inputs-" + url;

//use a dictionary as the keys

var values = {};

jQuery("form input").each(function(){

values[jQuery(this).attr("name")] = jQuery(this).val();

});

try

{

localStorage.setItem(key, JSON.stringify(values));

}

catch(e)

{

localStorage.removeItem(key);

}

}

}

</script>

</head>

<body>

<form>

<table>

<tr>First Name: </tr><td><input type="text" name="fname" id="fname"></input></td>

<tr>Last Name: </tr><td><input type="text" name="lname" id="lname"></input></td>

<tr><td colspan="2" style="text-align:right"><button onclick="saveToLocalStorage(); return false;">Save</button></td></tr>

</table>

</form>

</body>

</html>

devDevelopmenthtml shellhtml5html5 localstoragelocalstorage
Previous
Next

Latest White Papers

  • Shifting Plans for 2020 & Beyond
  • Game On: How Brands Can Log Into A Diverse Multi-Billion Dollar Industry
  • What CCPA Means For Brands
  • How Google is Improving Consumer Data Privacy
  • Ways to Prepare for the Cookieless Future
  • See all White Papers

Featured Posts

  • Ad Age Names PMG #1 Best Place to Work in 2021
  • Hindsight 2020 & Looking Ahead to 2021
  • Preparing for Streaming’s Growth & The Future of TV Buying
  • MediaPost Names PMG Independent Agency of the Year
  • PMG Client Portfolio Trends During Amazon Prime Day 2020

Categories

  • Consumer Insights
  • Content
  • Creative Design
  • Data Analytics
  • Development
  • Digital TV & Video
  • Ecommerce
  • Industry News
  • Local
  • Mobile
  • Paid Search
  • PMG Culture
  • Programmatic & Display
  • SEO
  • Social Media
  • Structured Data
Fort Worth

2845 West 7th Street
Fort Worth, TX 76107

Dallas

3102 Oak Lawn Avenue
Suite 650
Dallas, TX 75219

Austin

823 Congress Avenue
Suite 800
Austin, TX 78701

London

33 Broadwick Street
London
W1F 0DQ

New York

120 East 23rd Street
New York, NY 10010

Get in touch

(817) 420 9970
info@pmg.com

Subscribe to the PMG Newsletter
© 2021 PMG Worldwide, LLC, All Rights Reserved
  • Contact
  • Privacy Policy
 Tweet
 Share
 Tweet
 Share
 Tweet
 Share
 LinkedIn
We and our partners use cookies to personalize content, analyze traffic, and deliver ads. By using our website, you agree to the use of cookies as described in our Cookie Policy.