Cookie is a small text file that's stored in user's browser. They're mostly used for storing user preferences. It save the data with name-value pair format. Following function can be used to create and retrieve cookie values.

Code Snippet

function setCookie(c_name,value,exdays)  
{
  var exdate=new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var c_value=escape(value) + ((exdays==null) ? "" : ";
  expires="+exdate.toUTCString());
  document.cookie=c_name + "=" + c_value;  
}

function getCookie(c_name)  
{   
   var i,x,y,ARRcookies=document.cookie.split(";");
   for (i=0;i<ARRcookies.length;i++)   
   {    
	   x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
	   y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
	   x=x.replace(/^\s+|\s+$/g,"");
	
	   if (x==c_name){ return unescape(y); }
   }  
}

Sample Usage

function checkCookie()  
{  
var username=getCookie("username");
    if (username!=null && username!="")
    {    
		alert("Welcome again " + username);    
	}
	else
	{    
		username=prompt("Please enter your name:","");
		if (username!=null && username!="")
		{
		setCookie("username",username,365);
		}
    }
}

Note

The function above makes an array to retrieve cookie names and values, then it checks if the specified cookie exists, and returns the cookie value. Last, we create the function that displays a welcome message if the cookie is set, and if the cookie is not set it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function: The example above runs the checkCookie() function when the page loads.


Reference/Credit

W3S




author's photo

Author : Blue Cloud

Just a normal software developer who love to write code. Developing professional software since 1999. After working in the software industry for many years, I've started my own website to share knowledges and experiences.

COMMENTS
blog comments powered by Disqus