Categories
Uncategorized

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);
}

By Moazzam

Moazzam is a software developer working in the big apple. He has over a decade of experience in development. While most of his work involves developing web applications, he does development for Android and Windows Mobile in his spare time.

2 replies on “Setting, removing and reading cookies in Javascript”

Leave a Reply

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