chatch.es

programming and diy
by philip kelly

Quick lists using localStorage and contentEditable

September 20th 2010

screenshot example of quick lists I've been playing around with some newfangled html5 techniques. Specifically localStorage to easily persist data on a client browser, and contentEditable to allow editing of html on the fly. Hop on over to chatch.es/workshop/lists/ if you want to go straight to the demo.

I ran across this demo on html5demos.com which shows off editing some elements and saving them with localStorage so you can refresh the browser and your changes are still there. This is pretty neat in itself, but I ran with the concept and created a quick client-side task list.

Features

  • Create, edit, remove, and complete items.
  • Add nested lists.
  • Save multiple lists by keying each one with a URL param (ex: chatch.es/workshop/lists/?MyList).
  • Lists have their name set as the page title. Making for nice bookmark-able lists.
  • Persisting list, even after browser is closed.

Under the hood

Each editable field has the contenteditable attribute set.

<h1 contenteditable="true"></h1>

Each keystroke on an editable field will trigger the save_state javascript helper function, which saves everything in the body element. A better solution would be to separate the markup from the data when saving, however the markup would have to be rebuilt with javascript on page load. Not worth the time to implement for a simple demo. The get_list_name function is another helper that checks the URL for a list name. This keeps each separate list separate in the localStorage.

function save_state() {
  localStorage.setItem(get_list_name(), $('body').html());
}

When the page is loaded, localStorage is checked to see if data has already been saved, in which case it is used to replace the body's inner html.

if (localStorage.getItem(get_list_name())) {
  var saved_html = localStorage.getItem(get_list_name());
  $('body').html(saved_html);
}

jQuery is used to handle all the application logic. For a more detailed look, check out the lists.js file.

Take me to the demo

Runs great in Safari, Firefox, and Chrome. Unfortunately contentEditable doesn't yet work in Mobile Safari. I haven't tested it in Opera or IE.

blog comments powered by Disqus