Tuesday, September 21, 2010

jQuery & Cookies (get/set/delete & a plugin)

In this post I would like to share javascript functions that will help you easily get, set, delete and basically manage your cookies. Also, link to jQuery Cookie plugin, it’s improved version with more functions and of course easy to read and short examples on how to use these functions.

I will try to keep this post short and will not explain what cookies are and how to eat them. There are plenty of articles covering it already.

Here are javascript functions by Peter-Paul Koch to getCookie(), setCookie() and deleteCookie():

function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}
/*
  Changed function names from readCookie(), createCookie()
  and eraseCookie() to getCookie(), setCookie() and
  deleteCookie().
*/

Here is an example that shows you how to use those functions in your javascript to create, edit and delete your cookies:

// Create/write a cookie and store it for 1 day
setCookie('myCookie', 'myValue', 1);

// Get my cookie
getCookie('myCookie');

// Delete/erase my cookie
deleteCookie('myCookie');

These 3 javascript functions are all you need to manage your cookies, but if you want to do it in “jQuery style” than you can use jQuery Cookie plugin or it’s improved version.

Here is how to use jQuery Cookie plugin in your code:

// Setting a cookie
$.cookie('myCookie':'myValue');

// Creating cookie with all availabl options
$.cookie('myCookie2', 'myValue2', { expires: 7, path: '/', domain: 'example.com', secure: true });

// Get a cookie
$.cookie('myCookie');

// Delete a cookie
$.cookie('myCookie', null);
With an improved version of the plugin you can set and get multiple cookies in one call. The improved version of the jQuery Cookie pluin only adds few additional bytes. So it really worth it. 
// Set multiple cookies
$.cookie({ 'cookie1':'value1', 'cookie2':'value2' });

26 comments:

  1. I believe that

    $.cookie('myCookie':'myValue');

    should be

    $.cookie('myCookie','myValue');

    or

    $.cookie({'myCookie':'myValue'});

    ReplyDelete
  2. // Setting a cookie
    $.cookie('myCookie':'myValue');

    Um, excuse me?

    ReplyDelete
  3. Syntax correction in your very useful post above:

    $.cookie('myCookie':'myValue');
    gave me an error.

    the plugin's doc says to use:
    $.cookie('myCookie','myValue');

    Thanks for this info, much appreciated!
    Cheers!
    Terran

    ReplyDelete
  4. // Setting a cookie
    $.cookie('myCookie':'myValue');

    This should be
    $.cookie('myCookie','myValue');
    OR
    $.cookie({'myCookie':'myValue'});

    ReplyDelete
  5. Thank you, this helped me very much

    ReplyDelete
  6. in getCookie() you can avoid :

    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    but split document.cookie with "; " (notice the space at the end)
    every cookie start with only one space.

    ReplyDelete
  7. error:
    // Setting a cookie
    $.cookie('myCookie':'myValue');

    // Setting a cookie
    $.cookie('myCookie','myValue');

    ReplyDelete
  8. jQuery Cookie pluin only adds few additional

    Plugin not pluin

    ReplyDelete
  9. Setting a cookie using the jquery plugin, i believe you have a syntax error.

    Incorrect
    $.cookie('myCookie':'myValue');

    Correct
    $.cookie('myCookie','myValue');

    ReplyDelete
  10. Thank you for the no nonsense breakdown of jQwery & cookies, just what I needed.

    ReplyDelete
  11. At the end, i think it's better to have

    if(jQuery.isEmptyObject(returnValue)){
    return null;
    }else{
    return returnValue;
    }

    to be compatible with the former jquery cookie plugin tutorials all over the Internet

    ReplyDelete
  12. Note that to have the Jquery script to work an : is needed instead of a ,
    In the script itself in the comments an : is stated.

    ReplyDelete
  13. does these cookies last forever or do they work more like session cookies

    ReplyDelete
  14. I am pretty sure that setCookie() function is incorrect. I believe there is no need to multiply by 1000, as time is set in seconds.

    ReplyDelete
  15. Thanks for share this nice solution.

    ReplyDelete
  16. $.cookie("name":"value"); is not working !!!1

    ReplyDelete
  17. So how can i delete a cookie when i'm derecting to a webpage?

    I have set a cookie like this:

    var inNum;
    var outNum;
    var COOKIE_NAME = "my_carousel_position";

    // MANAGE COOKIES
    function setCookie(cName, cValue, cDaysNum)
    {
    var date = new Date();
    date.setTime(date.getTime() + (cDaysNum * 24 * 60 * 60 * 1000));
    $.cookie(cName, cValue, { expires: date });
    return false;
    }

    ReplyDelete
  18. how to set the cookie for 10 minutes instead of 1 day?

    ReplyDelete
  19. Local Data can store multiple values in a single cookie.

    https://github.com/pavelkukov/localdata

    It can set and get multiple values that use cookies to be shared between different server side scripts (php).

    The values are stored in cookies encoded in JSON format so they can be easily accessed on the browser side JavaScript code preserving the original value data types.

    A JavaScript library is provided to set and get values stored this way in cookies.

    ReplyDelete
  20. Hi, thanks for sharing. There is a bug in your code though...

    $.cookie('myCookie':'myValue');
    shold be
    $.cookie('myCookie','myValue');

    ReplyDelete
  21. Setting cookie has an error

    $.cookie('myCookie':'myValue');

    this above line should be like this

    $.cookie('myCookie','myValue');

    ReplyDelete
  22. As per w3 schools, toGMTString() is Deprecated. Use the toUTCString() method instead.

    ReplyDelete
  23. Hey, thanks for the article. Not afraid of cookies anymore ;)

    ReplyDelete