Cookies in Javascript

Jul8
  • Share

Difficulty: ★★☆☆☆
A cookie (also tracking cookie, browser cookie, and HTTP cookie) is a small string 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.
Beside the name/value pair, a cookie may also contain an expiration date, a path, a domain name, and whether the cookie is intended only for encrypted connections. These pieces of data follow the name=newvalue pair and are separated by semicolons. For example, a cookie can be created by the server by sending a line

Set-Cookie: name=newvalue; expires=date; path=/; domain=.example.org.

With Javascript you can also set cookies. It’s not hard at all. I think it’s useful for folding/unfolding or hiding/displaying CSS content. This part of Javascript I wrote for setting, getting and deleting a cookie:

/*
* Set the cookie
* @param name - the name of the cookie variable
* @param value - the value of the variable which will be saved in the cookie.
* @expires - the
*/
function setCookie(name, value, expires) {
	var today = new Date();  //set new date object
	var defaultDays = 30;
	today.setTime(today.getTime());
	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	}else{
		expires = defaultDays * 1000 * 60 * 60 * 24;
	}

	document.cookie = name + "=" + escape(value) +
        "; path=/" + ((expires == null) ? "" : "; expires=" +
        expires.toGMTString());
}

/*
 * Get Cookie
 * @param: name of the cookie variable you would like to retrieve
 */
function getCookie(name) {
	var cookieValue = null;
	var startPos = document.cookie.indexOf(name+"=");
	var lengthVal = startPos + name.length + 1;

	if((startPos)&&(startPos>0)&&
        (name == document.cookie.substring(0, name.length))){
		var endPos = document.cookie.indexOf( ";", lengthVal);

		if (endPos == -1){
			endPos = document.cookie.length;
		}
		cookieValue = unescape(
                   document.cookie.substring(lengthVal, endPos)
                );
	}

	return cookieValue;
}

/*
 * Delete Cookie
 * @param delete the cookie variable by passing the name
 */
function delCookie(name) {
    document.cookie = name +
    "=; expires=Thu, 01-Jan-70 00:00:01 GMT" + "; path=/";
} 


Leave a comment