Search code examples
javascriptajaxhtmllocal-storagedwr

Implement HTML5 localStorage


I am aware of the basics of using the HTML5 localStorage using the localStorage.getItem/setItem.

But I am trying to understand how to implement the same on my dynamic page. So here is the scenario:

I have a dynamic page (myPage.jsp) which on initial load calls a Java method (that outputs the HTML string) as below;

<div id="mainContainer">
    <div id="parent1"><span>Parent 1</span></div><ul id="child1"></ul>
    <div id="parent2"><span>Parent 2</span></div><ul id="child2"></ul>
    <div id="parent3"><span>Parent 3</span></div><ul id="child3"></ul>
</div>

Here the number of parent div's are dyanamic based on some logic.

Now on click on any of the parent divs, a Java method is called again (that again outputs the HTML string) for the child innerHTML. The HTML returned (on click of say Parent 2) is as follows;

<li class="listEle">Child content 1</li>
<li class="listEle">Child content 2</li>

Here the number of "li" elements are dynamic for each parent. Actually the above HTML is just appended to the mainContainer....So the overall HTML code looks like

<div id="mainContainer">
    <div id="parent1"><span>Parent 1</span></div><ul id="child1"></ul>
    <div id="parent2"><span>Parent 2</span></div><ul id="child2"><li class="childLi">Child content 1</li><li class="childLi">Child content 2</li></ul>
    <div id="parent3"><span>Parent 3</span></div><ul id="child3"></ul>
</div>

Now my question is I want to use localStorage for 2 things:

  1. Storing the initial HTML code (mainContainer) without any child content; AND
  2. Storing the child HTML code as well (which is within the mainContainer)

I am looking at the various ways in which I can do this. I am open to all ideas that you can think of. Just need to consider that all things are dynamic (number of parent divs/child li's, etc)...So need to know how I can handle that dynamic content.


Solution

  • You can store anything you like in localStorage provided the item stored is turned into a string, no problem in your case, and the total storage doesn't exceed 5Mb per site.

    You approach could something like this.

    1. When the page loads (use jQuery) check if the base HTML template is there
    2. If not use jQuery to load it and store it in localStorage
    3. use a jQuery selector to select the appropriate element in the current page. This could be the element. And use $(...).html(stored html template); to display the base html.
    4. If you need to insert dynamic values use something like John Resig MicroTemplating to insert variables.