JavaScript Cookies

What is Cookies?

A cookie is a variable that is stored by the site when we request a page with a browser. With JavaScript, we can both create and retrieve cookies values to process as our need.

In this tutorial we will see how to set and retrieve cookies with JavaScript. First, we will create a function that stores the time of the page is loading. Check the below code:

function setCookie(c_name,value,exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
document.cookie=c_name+”=”+escape(value)+”;expires=”+exdate.toGMTString();
}

 

The parameters of the setCookie()  function above hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires.

In the setCookie()  function we first create an object of JavaScript Date, then we add the number of days until the cookie should expire. After that we store the cookie name, cookie value and the expiration date in the document.cookie object.

Now, we will create another function that returns the cookie we specified as argument:

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

The getCookie( ) function makes an array to retrieve cookie names and values, then it checks if the specified cookie exists, and returns the cookie value.

Finally, we will create the show_message() function that displays a welcome message if the visitor visit the page for the first time in last 365 days, Or it will shows time the visitor visit the page last time, and later by calling the setCookie function we will update the cookies time.

function show_message() {
var exdate=new Date();
var last_visit_time=getCookie(“last_visit_time”);
if (last_visit_time!=null && last_visit_time!=””) {
document.getElementById(“msg”).innerHTML=”Last time You visit us on ” + last_visit_time;
} else {
document.getElementById(“msg”).innerHTML=”Welcome! You have visit us for the first time.”;
}
var time_cokie_value = exdate.toString();
setCookie(“last_visit_time”,time_cokie_value,365);
}

To see the result you must call the show_message()  on body tag using onload and add a div with “msg” id. It’s time to see the result. To download the full code please Click Here.

 

Author Info

  • Thanks alot! This is what i was looking for

  • diablo 3

    I received very good information from a web site

  • Pedro Saven

    I value you taking the time to publish this publish. It has long been quite valuable to me indeed. Enjoy it.