Skip to content

Instantly share code, notes, and snippets.

@benkn
Created April 16, 2015 20:08
Show Gist options
  • Save benkn/84c862aca55752daf3aa to your computer and use it in GitHub Desktop.
Save benkn/84c862aca55752daf3aa to your computer and use it in GitHub Desktop.
Ask users to enter their name and store it in a cookie.
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) {
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
}
function getCookie (name) {
var arg = name + "=";
var argLength = arg.length;
var cookieLength = document.cookie.length;
var i = 0;
while (i < cookieLength) {
var j = i + argLength;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal(j)
} else {
i++;
}
}
return null;
}
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
(expires ? ("; expires=" + expires.toGMTString()) : "") +
(path ? ("; path=" + path) : "") +
(domain ? ("; domain=" + domain) : "") +
(secure ? "; secure" : "");
}
// get a date that is exactly one week away from today
function getWeekFromToday() {
var d = new Date();
d.setDate(d.getDate() + 7);
return d;
}
(function() {
var username = getCookie('username');
if( !username ) {
username = prompt("Please enter your name", "");
if (username != null) {
setCookie('username', username, getWeekFromToday());
}
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment