Skip to content Skip to sidebar Skip to footer

Javascript - Using Cookies To Store An Integer

I am trying to use a cookie to store a single integer, so when the user refreshes the page I am able to retrieve the previous number they were on (in an attempt to stop doubles of

Solution 1:

Tamil's comment is solid. Use these quirksmode functions if you ever wish to surpass minimal cookie usage:

cookie_create = function (name,value,days) {
    var expires, date;

    if (days) {
        date = newDate();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    else expires = "";
    document.cookie = name+"="+value+expires+"; path=/";

expires = date = null;
};


cookie_read = function (name) {
    var nameEQ = name + "=",
    ca = document.cookie.split(';'),
    len = ca.length,
    i, c; 

    for(i = 0; i < len; ++i) {
        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);
    }

nameEQ = name = ca = i = c = len = null;
returnnull;
};


cookie_erase = function (name){
    cookie_create(name,"",-1);
name = null;
};

Solution 2:

You could use document.cookie to read/write cookies in javascript:

document.cookie = 'mycookie=' + randomNumber + '; path=/';

And if you wanted the cookie to be persistent even after the user closing his browser you could specify an expires date.

Post a Comment for "Javascript - Using Cookies To Store An Integer"