Working with cookies and JavaScript

Hi,

 

I have discussed about cookies in my previous posts. But in all those posts I talked about working with cookies in server side.

You can read these posts here

   

In this post I will talk about working with cookies in the client side.

 

Many a times we want to work with cookies in the client side itself. We can use JavaScript to create, read and delete cookies. This can increase the productive way to work with cookie. We can access the cookies in the JavaScript with the help of the property document.cookie

 

To create a new cookie we can use the following line of code.


document.cookie = vikcookie1=VikFirstCookie; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/


Here first we provide the Name value pair, then the expire date in give format (being separated with ; and space) and then the path (again separated with ; and space). You can set many cookies like this by just changing the Name of the key in the cookie.

 

You can read a cookie with document.cookie. But this time the value returned will only be the name value pair. If there are more number of cookies for the domain then we will get multiple name value pair separated with semicolon and space. So the value returned by document.cookie will be something like

 

vikcookie1=VikFirstCookie; vikcookie2=VikSecondCookie

 

We can reset a cookie by overriding the cookie with the same name and different value or Expiry date.

 

To remove a cookie all we have to do is to modify a cookie with the expiry date set to date before today. When the browser finds that the cookie has expired it will be automatically remove the cookie.

 

Vikram

No Comments