Quantcast
Viewing latest article 4
Browse Latest Browse All 4

Create, modify and read a Cookie with JavaScript

The first function creates or modifies a cookie. The second one returns the value of a cookie.

JavaScript code:

setCookie("MyCookie", "jump", 7); // The Cookie "MyCookie" has the value "jump" and expires in 7 days.

function setCookie(c_name, value, expiredays){
    var exdate = new Date();
    exdate.setDate(exdate.getDate()+expiredays);

    document.cookie = c_name+"="+escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

JavaScript code:

readCookie("MyCookie"); // Returns value "jump".

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


Viewing latest article 4
Browse Latest Browse All 4

Trending Articles