Using cookies without JQuery

Sometimes is necessary to be able to access cookies (read/write) from vanilla Javascript. For example if we are using JQuery 2.0, that doesn’t support IE8, but we need to manage some behavior for the other browsers, such as a message that warn the user about using an obsolete browser and that needs a cookie to not be displayed after the user pressed OK.

function ie8_setCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setDate(date.getDate() + days);
        expires = ";expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + escape(value) + expires + ";path=/";
}
 
function ie8_getCookie(name) {
    var i, x, y, cookies = document.cookie.split(";");
    for (i = 0; i < cookies.length; i++) {
        x = cookies[i].substr(0, cookies[i].indexOf("="));
        y = cookies[i].substr(cookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == name) {
            return unescape(y);
        }
    }
    return null;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s