Grow your CSS skills. Land your dream job.

Last updated on:

Cookie Getter/Setter

/**
 * Gets or sets cookies
 * @param name
 * @param value (null to delete or undefined to get)
 * @param options (domain, expire (in days))
 * @return value or true
 */
_.cookie = function(name, value, options)
{
    if (typeof value === "undefined") {
        var n, v,
            cookies = document.cookie.split(";");
        for (var i = 0; i < cookies.length; i++) {
            n = $.trim(cookies[i].substr(0,cookies[i].indexOf("=")));
            v = cookies[i].substr(cookies[i].indexOf("=")+1);
            if (n === name){
                return unescape(v);
            }
        }
    } else {
        options = options || {};
        if (!value) {
            value = "";
            options.expires = -365;
        } else {
            value = escape(value);
        }
        if (options.expires) {
            var d = new Date();
            d.setDate(d.getDate() + options.expires);
            value += "; expires=" + d.toUTCString();
        }
        if (options.domain) {
            value += "; domain=" + options.domain;
        }
        if (options.path) {
            value += "; path=" + options.path;
        }
        document.cookie = name + "=" + value;
    }
};

Reference URL

Comments

  1. nick
    Permalink to comment#

    How do you use this?

    • Samuel0Paul
      Permalink to comment#

      well just add the js code and access the function with the corresponding options…

      call the function by sending @value as “undefined” to get the value of the cookie named <name>
      to set a “value” for a cookie named <name> call the function with @name as <name> and @value as “value

  2. Permalink to comment#

    Wow dirty ! Based on both Underscore.js (I guess) and jQuery and not even specified. Oo’

  3. tyl

    yea how do u this chunk of codes?!

Leave a Comment

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".