Confirm if a user is minimum 18 [JavaScript Code]

A simple code snippet implemented with SweetAlert2.

Confirm if a user is minimum 18 [JavaScript Code]

First include SweetAlert2 by follwing the instructions or just adding the following version via CDN:

And here's the script, please adapt the texts to your needs. In this versino the script repeatedly asks until you confimred that you're 18 or older.

function setCookie( c_name, value, exdays ) { var c_value = escape(value); if (exdays) { var exdate = new Date(); exdate.setDate( exdate.getDate() + exdays ); c_value += '; expires=' + exdate.toUTCString(); } document.cookie = c_name + '=' + c_value; } function getCookie( c_name ) { var i, x, y, cookies = document.cookie.split( ';' ); for ( i = 0; i < cookies.length; i++ ) { x = cookies[i].substr( 0, cookies[i].indexOf( '=') ); y = cookies[i].substr( cookies[i].indexOf( '=') + 1 ); x = x.replace( /^\s+|\s+$/g, '' ); if ( x === c_name ) { return unescape( y ); } } } function askForAgeUntilConfirmed() { Swal.fire({ title: "Access to this page is only allowed if you're 18 years or older.", text: "Please verify your age", showDenyButton: true, confirmButtonText: "Yes, I'm at least 18", denyButtonText: "No, I'm not 18 yet.", }).then((result) => { if (result.isConfirmed) { setCookie('ageVerified', 'yes', 90); } else if (result.isDenied) { askForAgeUntilConfirmed(); } }); } jQuery(document).ready(function(){ if (!getCookie('ageVerified')) { Swal.fire({ title: "Are you 18 or older?", showDenyButton: true, confirmButtonText: "Yes, I'm at least 18", denyButtonText: "No, I'm not 18 yet.", }).then((result) => { if (result.isConfirmed) { setCookie('ageVerified', 'yes', 90); } else if (result.isDenied) { askForAgeUntilConfirmed(); } }); } });

An alternative would be to send the visitors to another page like disney.com:

function setCookie( c_name, value, exdays ) { var c_value = escape(value); if (exdays) { var exdate = new Date(); exdate.setDate( exdate.getDate() + exdays ); c_value += '; expires=' + exdate.toUTCString(); } document.cookie = c_name + '=' + c_value; } function getCookie( c_name ) { var i, x, y, cookies = document.cookie.split( ';' ); for ( i = 0; i < cookies.length; i++ ) { x = cookies[i].substr( 0, cookies[i].indexOf( '=') ); y = cookies[i].substr( cookies[i].indexOf( '=') + 1 ); x = x.replace( /^\s+|\s+$/g, '' ); if ( x === c_name ) { return unescape( y ); } } } jQuery(document).ready(function(){ if (!getCookie('ageVerified')) { Swal.fire({ title: 'Bist Du über 18?', showDenyButton: true, confirmButtonText: 'Ja, ich bin über 18', denyButtonText: 'Nein, ich bin unter 18', }).then((result) => { /* Read more about isConfirmed, isDenied below */ if (result.isConfirmed) { setCookie('ageVerified', 'yes', 90); } else if (result.isDenied) { window.location.replace("https://www.disney.com/"); } }); } });