Skip to content

Instantly share code, notes, and snippets.

@ShuvoHabib
Last active February 16, 2018 14:25
Show Gist options
  • Save ShuvoHabib/6467adf88fd8b0a9a3c0966c6342dcb4 to your computer and use it in GitHub Desktop.
Save ShuvoHabib/6467adf88fd8b0a9a3c0966c6342dcb4 to your computer and use it in GitHub Desktop.
Increment Cookie on Page Refresh
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function readCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
// Cookie Settings
var initCookie = 1;
var cookieName = "myCookie";
var getCookie = readCookie(cookieName);
// Under the Hood
if (getCookie == null) {
setCookie(cookieName, initCookie);
console.log('Cookie set to value 1');
} else {
if (getCookie >= initCookie) {
getCookie++;
setCookie(cookieName, getCookie);
console.log('Cookie incremented. Value is ' + getCookie);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment