Skip to content

Instantly share code, notes, and snippets.

@sumonst21
Created August 16, 2017 10:32
Show Gist options
  • Save sumonst21/2d3b310b6e41cd5018d067a490a01a0e to your computer and use it in GitHub Desktop.
Save sumonst21/2d3b310b6e41cd5018d067a490a01a0e to your computer and use it in GitHub Desktop.
A Function to Check a Cookie Last, we create the function that checks if a cookie is set. If the cookie is set it will display a greeting. If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:
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 getCookie(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 "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment