Last active
June 17, 2023 23:37
-
-
Save alison-mk/edffb54e5dc088fdd35a 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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Thank you for this snippet ❤️