Saving and reading cookies
If you want to read and save cookies the easy way you can use the two functions below from W3Schools. If the close element gets clicked I create a cookie named "closed" for which I set the value to "True". On the page load the cookie "closed" just gets checked if it was indeed already clicked.
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 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=/";
}
window.onload = function() {
if (getCookie("closed") == "True") {
document.getElementById('close').parentNode.parentNode.parentNode.removeChild(document.getElementById('close').parentNode.parentNode);
} else {
document.getElementById('close').onclick = function() {
setCookie("closed", "True", 42);
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
return false;
};
}
};
For more information about cookies click here.
Saving inside and reading from the localStorage
This is an example with localStorage which might be interesting for you since a localStorage item is almost like a cookie.
Once you click on the close element I store that it has been clicked inside the localStorage by using localStorage.setItem("closed","True");
. To now check if the element was already closed by the visitor on a previous visit etc. you can use localStorage.getitem("closed")
which will return "True" (in this case) and compare it to the String "True".
window.onload = function() {
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem("closed") == "True") {
document.getElementById('close').parentNode.parentNode.parentNode.removeChild(document.getElementById('close').parentNode.parentNode);
}
document.getElementById('close').onclick = function() {
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
localStorage.setItem("closed", "True");
return false;
};
} else {
alert("Your browser does not support localStorage");
}
};
Click here for a functioning jsfiddle.
For more information about localStorage I recommend W3Schools.