Setting, removing and reading cookies in Javascript

Copy/paste these methods and use them


/**
 * Create a cookie
 * 
 * @param string  name
 * @param mixed   value
 * @param int     days
 */
function createCookie(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=/";
}

/**
 * Read a cookie
 *
 * @param string  name 
 */
function readCookie(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;
}

/**
 * Remove a cookie
 * 
 * @param string  name
 */
function eraseCookie(name) {
    createCookie(name,"",-1);
}


Posted

in

by

Tags:

Comments

2 responses to “Setting, removing and reading cookies in Javascript”

  1. Nail Huseynli Avatar
    Nail Huseynli

    Salam aleykum, need to get in touch with you, how can I do it?

  2. Moazzam Avatar

    Walaikum assalam Nail,

    You can post in the comments section of this forum. I read the comments periodically. Did you need something from me?

Leave a Reply

Your email address will not be published. Required fields are marked *