556 CHAPTER 15 Local data with web storage
After this lesson, you will be able to:
■■Understand web storage.
■■Implement the localStorage object.
Estimated lesson time: 20 minutes
Understanding cookies
For years, storing data in the browser could be accomplished by using HTTP cookies, which
have provided a convenient way to store small bits of information. Today, cookies are used
mostly for storing basic user profile information. The following is an example of how cookies
are used.
// setting the cookie value
function setCookie(cookieName, cookieValue, expirationDays) {
var expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + expirationDays);
cookieValue = cookieValue + "; expires=" + expirationDate.toUTCString();
document.cookie = cookieName + "=" + cookieValue;
}
// retrieving the cookie value
function getCookie(cookieName)
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var index = cookie.indexOf("=");
var key = cookie.substr(0, index);
var val = cookie.substr(index + 1);
if (key == cookieName)
return val;
}
}
// usage
setCookie('firstName', 'Glenn', 1);
var firstName = getCookie('firstName');
Using the jQuery cookie plug-in
The example demonstrates that working with cookies isn’t complicated, but the interface for
doing so leaves much to be desired. To simplify working with cookies, you can use the jQuery.
Cookie plug-in available at https://github.com/carhartl/jquery-cookie. Here is the modified
code example when using the jQuery plug-in.