Numeric Values and Local Storage with HTML5 - dummies

Numeric Values and Local Storage with HTML5

By Andy Harris

With HTML5, you can write up to 5MB of data to a special localStorage file on the client computer. All the pages that come from your domain share the same storage area, so you can use this mechanism to keep data persistent between multiple pages. The data also stays on the client machine (until you remove it), so it can be used to keep track of information over time.

If you’re working with numeric data, remember that localStorage stores everything as a string. It’s no problem to store a numeric value in localStorage, but when you retrieve it, you’ll need to convert the value back to a numeric value (with parseInt() or parseFloat()) to the data type you need. Here’s an example that counts the number of times a user has visited your site:

  function countVisits(){
    str_count = localStorage.getItem("count");
    //get a numeric value from str_count, put it in count
    if (str_count == null || str_count == "null"){
      count = 0;
    } else {
      count = parseInt(str_count);
    } // end if
    //increment count
    //display count
    lblCounter = document.getElementById("lblCounter");
    lblCounter.innerHTML = "You have been here " + count + " times";
    //store count
    localStorage.setItem("count", count);
  } // end count

This code would need to be run every time the page is loaded (perhaps with the <body onload> attribute).

  1. Attempt to get the count from localStore.

    Use the str_ prefix to remind you that the data is currently a string.

  2. Ensure that the value exists.

    If there is no entry in the database for count, this must be the first time the user is here (or they have cleared the database). In either case, assign the value 0 to count (which is a numeric variable).

  3. If str_count exists, convert it to an integer.

    Use the parseInt() method to convert the string str_count into the integer count.

  4. Add one to count.

    Now that count is an integer, you can add to it.

  5. Display the counter value to the user.

    Of course, this is not absolutely necessary, but it’s nice to provide some feedback.

  6. Store count back to the localStorage database.

    Note that you can store the integer count to the database with no problems. It will be quietly converted to a string when it is stored.