Skip to content

Instantly share code, notes, and snippets.

@malachi358
Forked from alison-mk/age-verification.js
Created December 3, 2020 11:29
Show Gist options
  • Save malachi358/9ad6afb84b8bc5e63ed35a33120f2faa to your computer and use it in GitHub Desktop.
Save malachi358/9ad6afb84b8bc5e63ed35a33120f2faa to your computer and use it in GitHub Desktop.
Age verification cookie: Check cookie on every page load, display pop up window if no cookie is found. In every instance, set cookie to expire after one day. Live and in action here: http://www.leefoil.com/
ageVerify: 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;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i=0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) === 0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie() {
var age = getCookie("ageVerify");
if (age === "over21") {
// Check cookie: if exists and age passes, allow user into site
setCookie("ageVerify", "over21", 1);
} else {
// If cookie value is under 21, or if cookie does not exist, create modal window and ask user to respond
$('body').prepend("<div class=\"age-check\"><div class=\"text-wrapper\"><p>Are you 21 years or older?</p><button class=\"confirm\">Yes</button><button class=\"cancel\">No</button></div></div>");
// Get rid of modal once button is clicked
$('.age-check button').on('click', function() {
$('.age-check').hide();
});
$('button.confirm').on('click', function() {
// If user responds yes, change age value
age = "over21";
setCookie("ageVerify", "over21", 1);
});
$('button.cancel').on('click', function() {
// If user clicks cancel, direct user to /under-21 page
window.location.replace("http://www.leefoil.com/under-21");
setCookie("ageVerify", "under21", 1);
});
}
}
$(function() {
checkCookie();
});
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment