Chapter 7
Be Persistent with Local Storage

It is rare to have nary a need to store some information. No matter where you look, you might be asked to provide information, such as your name to join some service. Or you may be initiating retrieving some already stored information, such as looking up movies in your neighborhood by providing a ZIP code or city name. These uses involve a server and a database of some sort, which could be a standard SQL-based database such as MySQL or SQL Server, a text file, an XML file, and so forth. The point is that the data is stored in some traditional repository.

Along comes HTML5 and a new way to store information—without a database. In fact, you can even work without being hooked up to the Internet. The examples in this chapter work whether the pages are coming from a web server or just from within your computer.

Local Storage Defined

The term local storage needs a definition here, as it could be misleading. Information is stored within the browser. The internal mechanics of how this is done are not relevant to the discussion. The browser handles the storage and retrieval functions through an API. Storage is “local” in the sense that it’s essentially within the browser. However, this does not mean you need to work offline, just that you can.

The local storage concept is really one of persistent storage. This means information is maintained even after the browser session ends. You can navigate away from a web page or close the browser. If you saved data using the storage methods you’ll learn about in this chapter, then the data is retrievable. The next time you return to the web page, the data is there!

In the past, the methods for maintaining persistent information have been either through cookies or by keeping the information in a database on the server. Cookies have served us well for the most part, but have also been problematic. For example, a browser can be set to reject cookies. Cookies often need to have an expiration date set with them. (Without setting a date, cookies expire when the current browser session ends; they are gone when the browser is closed.) That makes the data they hold persistent, but how long should they last? Cookies are useful for holding small amounts of information, but nothing substantial.


NOTE

In case you’re not familiar with cookies, it’s not about the chocolate chip or oatmeal types. Cookies are small text files placed on a local computer, in a dedicated place, through the browser. They contain some information, such as a person’s name or a value last used. Typically, they hold only a small amount of information.


Saving data on the server is great. There is plenty of memory, and you can fill it up as needed. Server-based databases may easily hold megabytes of data. The catch with using a database on the server is the need for using a server-side language (such as ASP.NET or PHP) for working with the database.

Now, let’s look at an example of using the local storage functions. Later, you’ll see how to apply this technique to multimedia usage.

Basic Local Storage

Figure 7-1 shows a web page in which users enter a list of to-do tasks. The entry boxes are standard form-based text boxes (although no form is used, since no submitting is done). The user types each task into a box and clicks the Save Task button.

image

Figure 7-1 Setting up to use local storage

When the user closes the browser and then reopens it to the same page, the boxes are empty. Clicking a Get Task button will fill in the entry box with the original entry. Figure 7-2 shows how the first task has been retrieved.

image

Figure 7-2 Retrieving a stored data value

The storage is handled via a key/value relationship. This is a common configurable approach to storing values. In fact, think of a basic algebra expression: A=5. The value, 5, is assigned to the variable A. So far, just a numeric value is in play. Now consider the variable A equaling something other than a number; for example, A=Wash the dishes. This is how key/value pairs work. In the example, A is the key, and “Wash the dishes” is the value.

Here is a good place to show the code of the to-do task page (see Code Listing 7-1). Following it is an explanation of how the key/value pairing works using local storage.

Code Listing 7-1 A basic example of local storage

image

image

image

Each of the buttons—Store Task, Get Task, and Clear Task—passes an argument to a JavaScript function. The three JavaScript functions storetask, gettask, and cleartask each handles a method of the storage API.

The storetask function takes the passed argument, which is the name of the text box (used as the name of the key), and associates it with the entered value (value), as shown next.

image

In the function, the variable taskdetail is assigned the entered value. Then the setItem method of the localStorage object sets the association. This function is reusable and able to work with each of the entries.

The gettask function essentially reverses the storetask function. It calls back the stored value and places it in the text box:

image

The code is a single line that targets the text box (using document.getElementById) and setting its value to the stored value, by calling the getItem method. This method is given the name of the key, and the returned value is value.

When a web page is reopened, the gettask function pulls the value out of the browser. This is an important point. The browser retained the value, even though the browser was closed. Clearly, it stored the value somewhere, and that somewhere is on your local computer. Where on your computer that happens to be is left to how the browser manipulates its storage methods. You can ignore how the browser handles the storage and just depend on the browser to return values using the provided method.

Finally, there is a method to delete a stored value. The removeItem method of the localStorage object takes the passed argument (the name of a key), and internally deletes it. As this is accomplished, the text box displaying the value is set to be empty as well. This second action is not part of the storage facility, but rather just good programming practice.

image

Here is a summary of the three methods and their syntax:

image localStorage.setItem(key name, value) assigns the value to the key.

image localStorage.getItem(key name) returns the value assigned to the key.

image localStorage.removeItem(key name) deletes the key, along with the assigned value.

Now that we’re reviewed the basics, it’s time to focus on media manipulation.

Getting Visual

In a project I worked on, I needed to arrange four images into a single collage. The best arrangement of the four images was trial and error. I used an art program to move the images around, and then uploaded the assembled larger image to the server. This tedious work spurred the inspiration for the next demonstration. Using the local storage methods makes the task of arranging images easier.

The example in this section uses four images: an apple, a banana, a strawberry, and a watermelon. Each image is 75 × 75 pixels. Put together as two rows and two columns, the assemblage is a 150 × 150 pixel graphic. Moving the four components around is easy using absolute-positioned divs and assigning a particular fruit graphic to each div. To be clear, none of this has anything to do with local storage, yet. The key point of local storage is that it allows you to make an arrangement of the fruit images, and come back to that arrangement at a later time to continue working where you left off. In other words, the association of divs with the graphic assigned to each is remembered. Seeing it will make it clear. Figure 7-3 shows the layout of fruit images.

image

Figure 7-3 Arranged graphics for storage

As shown in Figure 7-3, the fruit is arranged by selecting from drop-downs. Each drop-down controls which fruit graphic is placed in one of the divs. No matter how you play around with arranging the graphics, the arrangement is stored and appears the way it was left when the browser was closed (or the page was navigated away from).

Code Listing 7-2 shows the code that makes the page and controls the graphics and storage. A discussion of pertinent points follows the listing.

Code Listing 7-2 Storing and retrieving an arrangement of graphics

image

image

image

image

image

The divs are set to absolute positions to ensure that the four graphics appear as one larger graphic. If you look at the left and top properties of the graphics, you can see how each one covers a quarter of the overall larger square. Each graphic is 75 × 75 pixels, so there is no need to set the width or height of the divs.

image

Each drop-down has an onchange event that calls the storepix function, sending it two arguments: the name of the drop-down itself and the div it is meant to alter. Actually, the second argument is just a number (1, 2, 3, or 4) that is concatenated with divfruit to match the name of the associated div. Next, setItem is used to create the key/value pair. The key name is the same as the drop-down (for convenience, not out of necessity), and the value is the name of the graphic file (such as apple.jpg). Finally, the selected graphic is placed in the div using the innerHTML property.

image

A default arrangement is used (apple, banana, strawberry, and watermelon) unless the graphics have been rearranged. When the page opens, JavaScript code runs to retrieve the stored values using the getItem method. The code is not in a function, and therefore runs whenever the page is rendered in the browser. This code snippet is placed toward the bottom of the overall page code so the divs are already rendered and in place before a graphic is placed in each.

So, the possibilities are that key/value pairs have been stored from previously using the page, it’s the first time the page is being opened, or the Clear Graphic button was used.

If it is the first time the page is displayed, then the variables being assigned the stored values will be null. Each variable is tested to see if a stored value (the name of a file) was found. If one is found, that graphic is displayed. If a variable is null, a default is used; for example, apple.jpg is used if fruit1 is null.

image

Finally, the code contains a JavaScript function to delete the saved keys and remove the graphics when the user clicks the Clear Graphic button. The function clearpix uses a for loop to iterate over the four divs, using removeItem of the localStorage object to delete the key/value pair, and setting the innerHTML property of the div to be empty.

image

The clearpix function is provided as a way to clear the combined graphic quickly, most likely to start over. In this case, with just four graphics, it doesn’t add much value. However, if this example were expanded to work with a larger number of graphics and divs, this ability would be useful as a time-saver.

Summary

The capability to save information with the browser as the repository streamlines and simplifies the process of storage. It’s streamlined in the sense that storage happens with no interaction with the web server and, likely, a remote database. This removes a bit of bandwidth usage—not much in most cases, but a bit here and a bit there adds up. Imagine a web site with hundreds of pages, each needing to store data for some function the site offers.

Stored values are accessible from other pages, as long as the same browser is used, and any other such pages use the getItem method with the same key name(s) used with the setItem method. In other words, values are stored from one page and retrieved from another page to be used for their intended purpose. A likely use of this approach is when form data is entered in more than one page. The values entered on each page are stored, and a final page in the entry process submits all of it to the server. However, between pages, the data is kept local until it is necessary to send it to the server at the last step. Why do this? To cut down on bandwidth. Big web sites need to save bandwidth and keep performance fast.

Subjectively, the best facet of local storage is working offline. When building a sophisticated web application, it is most often necessary to be online, with data going back and forth, to and from the web server (and probably the database). Local storage allows creating an application like this without being on the Internet—all the more reason to bring a laptop wherever you go!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.164.141