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?
views:
575answers:
3
+3
A:
Most of the old cookie handling functions I've seen use simple string manipulations for storing an retrieving values, like this example, you can use other libraries, like cookie-js, a small (< 100 lines) utility for cookie access.
I personally use jQuery on my projects, and I use the jQuery Cookie Plugin, it's really simple to use:
var cookieName = "increment";
if ($.cookie(cookieName) == null){
$.cookie(cookieName, 1, { expires: 10 });
}else{
var newValue = Number($.cookie(cookieName)) + 1;
$.cookie(cookieName, newValue, { expires: 10 });
}
CMS
2008-11-04 04:17:19
+5
A:
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.toGMTString();
}
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')) | 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)
nickf
2008-11-04 04:24:54
readCookie returns a substring, you should cast it as a number when incrementing 1, otherwise you will have, 1, 11, 111, 1111...
CMS
2008-11-04 06:58:58