HTML5 Zone
HTML5 Zone is brought to you in partnership with:
spacer spacer Raymond Camden
  • Bio
  • Website
  • @cfjedimaster

Raymond Camden is a developer evangelist for Adobe. His work focuses on web standards, mobile development and Cold Fusion. He's a published author and presents at conferences and user groups on a variety of topics. He is the happily married proud father of three kids and is somewhat of a Star Wars nut. Raymond can be reached via his blog at www.raymondcamden.com or via email at raymondcamden@gmail.com Raymond is a DZone MVB and is not an employee of DZone and has posted 42 posts at DZone. You can read more from them at their website. View Full User Profile

LocalStorage Example: Storing Previous Searches

07.17.2012
spacer Email
Views: 2246
  • Tweet
  • spacer
The HTML5 Microzone is presented by DZone and Microsoft to bring you the most interesting and relevant content on emerging web standards.  Experience all that the HTML5 Microzone has to offer on our homepage and check out the cutting edge web development tutorials on Script Junkie, Build My Pinned Site, and the HTML5 DevCenter.

Related MicroZone Resources

Insider Tips for Windows 8 HTML5 Development

Windows 8 HTML5 Layouts

Early Access! Windows 8 SDK

Visual Studio Express 2012 for Win 8 is FREE!

Windows 8 HOLO Series

Like this piece? Share it with your friends:

| More

I've made it clear that I'm a huge fan of LocalStorage. While sitting in the Houston airport for many hours this week, I decided to whip up a little example that demonstrates one of the practical uses for this feature. I built a simple Ajax-based search page and then added LocalStorage as a way to remember your previous searches. This isn't anything special, but I think it's another good example of the feature. Let's begin by taking a look at the application before any use of LocalStorage.

The application makes use of Bootstrap, jQuery, and Handlebars, but for now, let's just focus on the JavaScript and the template:

<script>
    $(document).ready(function() {

      var source = $("#artResultsTemplate").html();
      var template = Handlebars.compile(source);

      $("#searchButton").on("click", function(e) {
        e.preventDefault();
        var search = $.trim($("#search").val());
        if(search === '') return;
        console.log("search for "+search);
        $.get("service.cfc?method=searchArt", {term:search}, function(res,code) {

          var html = template({results:res});
          $("#results").html(html);
        },"JSON");

      });
    });
    </script>

  <script id="artResultsTemplate" type="text/x-handlebars-template">
    <h1>Results</h1>
    {{#if results}}
      <ul class="thumbnails">
      {{#each results}}
        <li class="span3">
          <div class="thumbnail">
            <img src="/img/spacer.gif"> 

You can see that I begin by compiling my Handlebars template (this is used for the results), and then I define my click handler for the search button. All the handler does is grab the search string, pass it to a ColdFusion service that hits the database, and then passes the results to my Handlebars template.

spacer

Beautiful - and the code is rather simple. You can test this yourself here: www.raymondcamden.com/demos/2012/jul/13/test1.html I'd recommend searching for oil, moon, paint, and beer.

Ok, now let's talk about the next version. The updated version will use LocalStorage to remember your last five searches. I decided on five mostly because it just felt right. I thought ten might be a bit much.

To store the last five values, I'll use an array. You can't store complex variables in LocalStorage, but you can easily serialize them with JSON. So for example:

var pastSearches = [];

if(localStorage["pastSearches"]) {
     pastSearches = JSON.parse(localStorage["pastSearches"]);
}

That isn't too complex, is it? Storing the value isn't too hard either. I do a check to see if the value exists in the array, and if not, put it in the front and pop one off the end if the array is too big.

if(pastSearches.indexOf(search) == -1) {
     pastSearches.unshift(search);
     if(pastSearches.length > 5) {
        pastSearches.pop();
     }
     localStorage["pastSearches"] = JSON.stringify(pastSearches);
}

 All that's left then is to simply write out the past searches and listen for click events on them.

function drawPastSearches() {
    if(pastSearches.length) {
        var html = pastSearchesTemplate({search:pastSearches});
        $("#pastSearches").html(html);
    }
}

$(document).on("click", ".pastSearchLink", function(e) {
    e.preventDefault();
    var search = $(this).text();
    doSearch(search);
});

 And voila - I can now remember your last five searches and provide an easy way for you to quickly rerun them. The code samples above are only the most important bits. I encourage you to View Source on the updated version for the complete example. (The ColdFusion code is just a simple query API. You can view that template here.)

Published at DZone with permission of Raymond Camden, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:
  • HTML & XHTML
HTML5 is the most dramatic step in the evolution of web standards. It incorporates features such as geolocation, video playback and drag-and-drop. HTML5 allows developers to create rich internet applications without the need for third party APIs and browser plug-ins.  Under the banner of HTML5, modern web standards such as CSS3, SVG, XHR2, WebSockets, IndexedDB, and AppCache are pushing the boundaries for what a browser can achieve using web standards.  This Microzone is supported by Microsoft, and it will delve into the intricacies of using these new web technologies and teach you how to make your websites compatible with all of the modern browsers.
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.