<< Back
Javascript cookie using warning - check & set
Javascript cookie using warning - check & set
Javascript cookie using warning - check & set
The html - the actual warning that we are going to use, in cakephp this is an element we include.
<div class="row cookiebox" id="cookiebox" onclick="setCookie();"> <div class='col-md-12'> <div class='box' style="background-color:#233242; color:#fff;"> <p style="float:right; padding-right:5px;">×</p> <p style="padding:10px;">To help personalise content, we might use cookies in the future. We currently don't use cookies relating to personal information</p> </div> </div> </div>
Here is the javascipt we are going use - NOTE you need jquery
function setCookie() { exdays = 365; var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires=" + d.toGMTString(); document.cookie = 'permission' + "=" + 'granted' + ";" + expires + ";path=/"; $('#cookiebox').hide(); } function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.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 perm=getCookie("permission"); if (perm != "granted") { $('#cookiebox').show(); } }
The last thing to do is when the page load to check if the cookie exists, if it doesn't we display the warning, we do this this in the body tag
<body onLoad='checkCookie();'>
that's all for now folks !
Published: 28th February 2020 by Gabriel Kolbe - got the javascript from https://www.w3schools.com/js/js_cookies.asp and adjusted it