FOLLOW US
4dots Software CODE BLOG

How to create cookie that expires in N days

To create a cookie for N days with Javascript you can use the following function.
Name is the id of the cookie and value the desired value of the cookie and days the number of days after it will expire.


    function createCookie(name, value, days) {
        var expires;

        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        } else {
            expires = "";
        }
        document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
    }
For example to create a cookie that expires in one year :

    function createCookie(name, value) {
        createCookie(name, value, 365)
    }	

How to read a cookie

To read a cookie you can use the following function. Name is the id of the cookie.

    function readCookie(name) {
        var nameEQ = encodeURIComponent(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 decodeURIComponent(c.substring(nameEQ.length, c.length));
        }
        return null;
    }

How to erase a cookie

To erase a cookie you can use the following function. Name is the id of the cookie.

    function eraseCookie(name) {
        createCookie(name, "", -1);
    }


 

Please Donate!

Please Share!