I'm currently facing an issue while trying to set multiple cookies based on the existence of a div using JavaScript. On the first visit, I want to display the div to the user if it exists, then set a cookie (named redCookie) that expires in 3 days. Upon setting the cookie, the div should not be displayed on page refresh. However, after 3 days, I want the div to be shown again using redDiv.show()
.
Currently, the div appears on every page refresh. The cookie is indeed being set, but it keeps showing up every time. There seems to be a problem with my if statement, but I can't quite figure it out.
if ((redCookie === true) && (redDiv.length > 0))
Here is a link to the JSFiddle for reference: https://jsfiddle.net/9uh96bh7/
Below are my defined functions:
$( document ).ready(function() {
colourCookies();
});
function colourCookies () {
var redCookie = getCookie("red-cookie-name");
var redDiv = $('.red');
var yellowCookie = getCookie("yellow-cookie-name");
var yellowDiv = $('.yellow');
if ((redCookie === true) && (redDiv.length > 0)) {
redDiv.show();
setCookie("red-cookie-name", redCookie, 3);
console.log('Red cookie is set');
} else {
redDiv.hide();
}
if ((yellowCookie === true) && (yellowDiv.length > 0)) {
yellowDiv.show();
setCookie("yellow-cookie-name", yellowCookie, 3);
console.log('Yellow cookie is set');
} else {
yellowDiv.hide();
}
}
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=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.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 "";
}