FOLLOW US
4dots Software CODE BLOG
VEGAS Movie Studio

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 :
VEGAS Movie Studio

    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;
    }
Music Maker - Free Full Version

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!