Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "best" way to get and set a single cookie value using JavaScript

I want to increment a cookie value every time a page is referenced even if the page is loaded from cache. What is the "best" or most concise way to implement this?

like image 639
Jamey McElveen Avatar asked Nov 04 '08 03:11

Jamey McElveen


People also ask

Can you set a cookie in JavaScript?

Create a Cookie with JavaScriptJavaScript can create, read, and delete cookies with the document. cookie property. With JavaScript, a cookie can be created like this: document.

How do I find the value of a specific cookie?

in order to retrieve specific cookie value, we just need to get string that is after "; {name}=" and before next ";". Before we do any processing, we prepend the cookies string with "; ", so that every cookie name, including the first one, is enclosed with "; " and "=": "; {name}={value}; {name}={value}; ..."

How do you get cookies in JavaScript?

In JavaScript, we can create, read, update and delete a cookie by using document. cookie property. The following syntax is used to create a cookie: document.

Which of the syntax is correct to set cookie in JavaScript?

document. cookie = "key1 = value1;key2 = value2;expires = date"; Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.


1 Answers

Stolen from http://www.quirksmode.org/js/cookies.html#script

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toUTCString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(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;
}

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

using it:

var oldCount = parseInt(readCookie('hitCount'), 10) || 0;
createCookie('hitCount', oldCount + 1, 7);

as pointed out in the comments, you should cast to an int since cookies are stored and returned as strings. Using foo++ or ++foo will actually cast for you, but it's safer to know exactly what you're working with:

var x = "5";  // x = "5" (string)
x += 1;       // x = "51" (string!)
x += 5;       // x = "515" (string!)
++x;          // x = 516 (number)
like image 96
nickf Avatar answered Oct 25 '22 21:10

nickf