Cookie.js 1.55 KB
/**
 * A Singleton class to create, read and delete cookies
 * @author Chris Boden
 * @version 0.3
 */
Cookie = new function() {
    /**
     * Create a cookie for current domain
     * @param {String} name The name of the cookie by reference
     * @param {String} value The value of the cookie to be stored
     * @param {Integer} days The Number of days until the cookie expires
     * @returns null
     */
    this.create = function(name, value, days) {
        var expires = '';
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = '; expires= ' + date.toGMTString();
        }

        document.cookie = name + '=' + value + expires + '; path=/';
    }

    /**
     * Get the value of a cookie for this domain
     * @param {String} name The name of the cookie
     * @returns A string if cookie exists null if not
     */
    this.read = function read(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;
    }

    /**
     * Erases a cookie from the domain
     * @param {String} name Name of the cookie to erase
     * @returns null
     */
    this.erase = function(name) {
        Cookie.create(name, '', -1);
    }
}