Learn jQuery

jQuery Cookie

Cookie is used for storing data on client side.Here we learn about jQuery.cookie, a jQuery plugin which makes cookie handling easy.

How to Download jQuery.cookie

You can download jQuery.cookie plugin from here.

How to Install jQuery.cookie

Once you have downloaded jQuery.cookie.js,you simply need to add it in your page after the jQuery library.

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
</head>

Create cookie

Each cookie has a name-value pair that contains the information.

Syntax

$.cookie('name', 'value');

Create expiring cookie

Syntax

$.cookie('name','value',{ expires: 10 }); // cookie will expire in 7 days

Read cookie

To read cookie we just need to pass cookie name as parameter.

Syntax

$.cookie('name');

Read all cookie

Syntax

$.cookie();

Delete cookie

To delete cookie we will use removeCookie() method.This method return true if the requested cookie is found, and false otherwise.

Syntax

$.removeCookie('name');

Note:When you are deleting a cookie, you must pass the exact same path, domain and secure options that were used to set the cookie,otherwise the operation will fail.

Cookie Options

$.cookie("name",'joe', {
   expires : 10,        //expires in 10 days
   path    : '/',       //define the path where the cookie is valid.
   domain  : 'tutsway.com',  //define the domain where the cookie is valid.                     
   secure  : true      //If it is true, the cookie transmission requires a secure protocol (https).                
});

Example

Here we expire a cookie in 10 minutes using jQuery.cookie plugin.

var date = new Date();
var minutes = 10;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie("name", "tutsway", { expires: date });