We begin the first of our demos. This looks at building a basic stickies option, as a practical introduction to using Local Storage.
For this recipe, you will need your normal text editor, as well as the code that accompanies this book.
Perform the following steps, to build a stickies option for using in a browser:
stickies.html
:<!DOCTYPE html> <head> <title>Storing content using Stickies and LocalStorage</title> <meta charset="utf-8" /> <link href= "http://fonts.googleapis.com/css?family= Reenie+Beanie:regular" rel="stylesheet" type="text/css"> <link rel="stylesheet" type= "text/css" href="css/stickies.css"> <script type="text/javascript" src= "http://code.jquery.com/jquery-1.8.3.min.js"></script> <script type="text/javascript" src="js/stickies.js"></script> </head> <body> <div id="postit-pad"> <pre id="postit" contenteditable="true" onkeyup="storeSticky(this.id);"></pre> <a class="clearStorage" href='' onclick= 'javascript:clearLocal();'>Clear local storage</a> </div> <script> getSticky(); </script> </body> </html>
LocalStorage
. Go ahead and add the following into a new document called stickies.js
, in the subfolder js
:function storeSticky(id) { var scribble = $("#postit").text(); localStorage.setItem('userScribble',scribble); } function getSticky() { if ( localStorage.getItem('userScribble')) { var scribble = localStorage.getItem('userScribble'), } else { var scribble = 'You can scribble directly on this sticky...and I will also remember your message the next time you visit!'; } document.getElementById('postit').innerHTML = scribble; } function clearStorage() { clear: localStorage.clear(); return false; }
img
and css
into the same location as your HTML and JavaScript files.This is a nice simple example of how you can use Local Storage to create a useful application, even if ours would need more work before it becomes a polished saleable application! In this instance, we've used a mix of plain JavaScript and jQuery—not out of necessity, but as a means to illustrate that you can achieve the same result using either method.
We've created a simple framework within a <div>
element called postit-pad
, which is styled using CSS2 and CSS3 rules. Within the stickies.js
file, we've created three simple functions—one to save content to LocalStorage
, one to retrieve it, and one to remove it from LocalStorage
(if desired). All three still use the methods that we've covered in this book. The difference here is that we are using native methods, rather than a polyfill or external library.
Let's move on and take a look at another demo, which is more of a proof of concept, and will show you how you can use Local Storage to create a basic to-do list, as you will see in the next recipe.