O'Reilly logo

jQuery Cookbook by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

17.1. Using Client-Side Storage

Problem

You are writing a rich Internet application that processes nontrivial amounts of user data in the web browser. Motivated by the desire to cache this data for performance reasons or to enable offline use of your application, you need to store data on the client.

Solution

A simple to-do list will be used to illustrate storing data on the client. As with many of the recipes in this chapter, a jQuery plugin will be used to handle browser inconsistencies:

<!DOCTYPE html>
<html><head>
    <title>17.1 - Using Client-Side Storage</title>
    <script type="text/javascript" src="../../jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="jquery.jstore-all.js"></script>
</head>

<body>
    <h1>17.1 - Using Client-Side Storage</h1>
    <p>Storage engine: <span id="storage-engine"></span></p>
    <input id="task-input"></input>
    <input id="task-add" type="submit" value="Add task"></input>
    <input id="list-clear" type="submit" value="Remove all tasks"></input>
    <ul  id="task-list"></ul>
</body></html>

The HTML consists of form elements for manipulating the to-do list: a text field to input a task, and buttons for adding a task and deleting all tasks. The current tasks will be listed using an unordered list:

(function($) {
    $.jStore.ready(function(ev,engine) {
        engine.ready(function(ev,engine) {
            $('#storage-engine').html($.jStore.CurrentEngine.type);
            $('#task-list').append($.store('task-list'));
        });
    });

The jStore plugin provides two callbacks: jStore.ready() and engine.ready() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required