i have a set of top messages that serve as alerts. They have an X to close them. Closing them sets a cookie that make them disappear forever, the name of the cookie is taken from the id
of the specific top message you close.
i have a base code for creating, reading and erasing the cookie which goes like this:
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else
var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
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, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
and i create the dynamic-named cookies like this:
if ($(".timed-top-message").size() > 0) {
$(".timed-top-message").on("click", "i", function() {
var CookieUniqueIdentifier = $(this).parent().attr("id")
$(this).parent().fadeOut(200);
createCookie(CookieUniqueIdentifier, 'true', 100000)
console.log('cookie created');
});
}
and this does the job. My problem is when i have to read the cookie. This throws an error:
(function() {
var checkForCookiez = readCookie(CookieUniqueIdentifier); // i read the cookie
if (!checkForCookiez) { // if it doesn't exist
console.log('it does not exist')
} else{ // if it does exist
console.log('it does exist')
}
})();
the error is
app.js:1142 Uncaught ReferenceError: CookieUniqueIdentifier is not defined
i get that CookieUniqueIdentifier
is scoped inside a click function, and it can't retrieve it. But what i want to achieve is a system to dinamically creating cookies named by a unique id
and consequently read them in a dynamic way.
I'm not very good with jquery and i was wondering if I'm on the right path or not. any suggestion is greatly appreciated.
I think the best approach here would be to read the cookie before showing the alert message(s) (on page load) and only show the alert if the cookie does not exist. You haven't shown that part of the code but if you include it I'd be happy to add the relevant code updats here.