Cookie and Javascript: How to Handle

Depend on the definition from Wikipedia: "A cookie, also known as a tracking cookie, browser cookie, and HTTP cookie, is a text file stored as plain text on a user's computer by a web browser. A cookie consists of one or more name-value pairs containing bits of information, which may be encrypted for information privacy and data security purposes". Since cookie invented, it almost is an indispensable factor to any web application or any browser.

If you are still vague about cookie and how to use it then this free JavaScript article maybe better. From the knowledge of this JavaScript article, you are able to create, store and access the cookie on your web application.


Sampled by © JavaScriptBank.com

Introduction

This is my very first weekly tips for web design and development. From now on, I'll be posting it every week, and will cover all sort of interesting, helpful web design and development tips and tricks.

"In computing, a cookie (also tracking cookie, browser cookie, and HTTP cookie) is a small piece of text stored on a user's computer by a web browser. A cookie consists of one or more name-value pairs containing bits of information such as user preferences, shopping cart contents, the identifier for a server-based session, or other data used by websites." - Wikipedia - HTTP Cookie

Relates:
- Cookies in JavaScript
- JavaScript Delicious Cookies
- JavaScript Cookie Enabled script

Yes, we'll look into how to manipulate cookies using Javascript. Just in case f you have no ideas what cookies can do, below are the two major usages:

  • Store authentication/session: Have you notice that remember me checkbox under the login box? It uses cookie to remember you. It stores your session details so that you don't have to login when you visit the website again.
  • Store data: You can use cookie to store data in client's computer. For example, Displaying a "welcome back" message or automatically fill in the username field. Or you can use it to remember the position of the current selected menu item, selected tab or position of elements
Advantages
  • Cookies do not use server resources since it stores in client's computer.
  • Expiry date of cookies can be configured.
  • Easy to implement.
Diadvantages
  • Users can delete a cookies.
  • Browsers can be set to decline cookies (By default, all browsers accept cookies).
  • Cookie stores data in plain text thus a potential security threat.
  • It can store huge amount of data

Create, Modify and Erase Cookie

We have to understand how it works before we can go further, the structure of cookie is simple, it's made of:

  1. Name-value pair which stores the data.
  2. Expiry date, after which time the entry will be deleted.
  3. Web domain and path that the cookie should be associated with.
/* assume today date is 2009-09-09 */
/* Create a cookie that will expire 2 days later */
document.cookie = "name=kevin; expires=Fri, 11-Sep-2009 23:59:59 GMT; path=/";

/* Reassign value */
document.cookie = "name=queness; expires=Fri, 11-Sep-2010 23:59:59 GMT; path=/";

/* Erase a cookie, put a past date */
document.cookie = "name=queness; expires=Fri, 08-Sep-2009 23:59:59 GMT; path=/";

Cookie Functions to Make Your Life Easier

Kudos to Quirksmode.org, they have created these functions to create, read and erase cookie easily. We don't even have to remember the GMT date format, we just have to set number of days and it will do the rest for us. Pretty good huh?

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

A Simple Implementation Menu

Alright, a really simple real implementation, it remembers which menu item you have just clicked, and the script assign a selected class to it. It highlights the current menu item.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 
	"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>untitled</title>
	<script type="text/javascript" src="js/jquery-1.3.1.min.js"></script>
	<link type="text/css" rel="stylesheet" href=""/>
	<script>
	
	$(document).ready(function () {

		//for debugging purpose, so that you can see what is in the menu cookie
		$('#debug').html('Cookie Content : ' + readCookie('menu'));

		//if cookie menu exists
		if (readCookie('menu')) {
			
			//loop through the menu item
			$('#menu a').each(function () {
				//match the correct link and add selected class to it
				if ($(this).html() == readCookie('menu')) $(this).addClass('selected');
			});	
		}

		$('#menu a').click(function () {

			//Set the cookie according to the text in the link
			createCookie('menu', $(this).html(),1);
		});
		
	});


	/* Cookie Function */
	function createCookie(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	function eraseCookie(name) {
		createCookie(name,"",-1);
	}

	</script>
	
	<style>
	ul {
		padding:0;
		margin:0;
		list-style:none;
	}
	
		li {
			float:left;
			margin:0 10px;

		}
		
		li a {
			border-bottom:3px solid #ccc;	
			text-decoration:none;
			display:block;
			color:#666;
		}
		
		li a:hover {
			border-bottom:3px solid #000;					
		}
		
		li a.selected {
			border-bottom:3px solid #000;					
		}
		
	.clear {
		clear:both;	
	}
	</style>
</head>
<body>

<ul id="menu">
<li><a href="index.html">Home</a></li>
<li><a href="index.html">Tips</a></li>
<li><a href="index.html">Porfolios</a></li>
<li><a href="index.html">About</a></li>
<li><a href="index.html">Contact</a></li>
</ul>

<div class="clear"></div>

<br/><br/>
<div id="debug"></div>

</body>
</html>

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
How to open a car sharing service
Vue developer as a vital part of every software team
Vue.js developers: hire them, use them and get ahead of the competition
3 Reasons Why Java is so Popular
Migrate to Angular: why and how you should do it
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website
How To Create A Successful Prototype For Your PCB


Top view articles
Top 10 Beautiful Christmas Countdown Timers
Adding JavaScript to WordPress Effectively with JavaScript Localization feature
65 Free JavaScript Photo Gallery Solutions
16 Free Code Syntax Highlighters by Javascript For Better Programming
Best Free Linux Web Programming Editors
Top 10 Best JavaScript eBooks that Beginners should Learn
Top 50 Most Addictive and Popular Facebook mini games
More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
Top 10 Free Web Chat box Plug-ins and Add-ons
The Ultimate JavaScript Tutorial in Web Design


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com