Cookies and jQuery

To use cookies with jQuery, you will need the special Cookie plugin.

Setting cookies :

Setting cookies with the Cookie plug-in is quite intuitive:

   1: $(document).ready(function(){

   2:  

   3:     // Setting a kittens cookie, it will be lost on browser restart:

   4:     $.cookie("kittens","Seven Kittens");

   5:  

   6:     // Setting demoCookie (as seen in the demonstration):

   7:     $.cookie("demoCookie",text,{expires: 7, path: '/', domain: 'demo.tutorialzine.com'});

   8:  

   9:     // "text" is a variable holding the string to be saved

  10: });

Reading cookies :

Reading a cookie is even simpler. Just call the $.cookie() function with a single cookie-name parameter, and the value of the cookie will be returned:

   1: $(document).ready(function(){

   2:  

   3:     // Getting the kittens cookie:

   4:     var str = $.cookie("kittens");

   5:  

   6:     // str now contains "Seven Kittens"

   7: });

Deleting cookies :

To delete a cookie, again use the $.cookie() function, but pass null as its second parameter.

   1: $(document).ready(function(){

   2:  

   3:     // Deleting the kittens cookie:

   4:     var str = $.cookie("kittens",null);

   5:  

   6:     // No more kittens

   7: });

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s