I'm new to javascript and I've been trying to program a cookie bar notice.
I have learnt how to use javascript to insert the cookie bar's html into the page and how to create a cookie with the name/value pair (CookieConsent=true) once the accept button is clicked.
But I have gotten stuck on - checking whether the specific cookie (CookieConsent=true) is present once the page has loaded and to do the following:
Im trying to make sure that the cookie check function is triggered when the page has loaded and have chosen to go with the EventListener - DOMContentLoaded for now.
Here is a basic example to illustrate my codes layout:
// When DOM has loaded trigger cookieCheck function
document.addEventListener('DOMContentLoaded', cookieCheck);
// Checks whether cookie is present and whether to execute cookiebar function or not
function cookieCheck() {
}
// Insert HTML for cookiebar notice and accept button into page
function cookiebar() {
// The accept button triggers the create cookie function with
// a name/value pair of CookieConsent=true
}
// Creates consent cookie
function createCookie() {
}
I'm not going to include the code I've attempted to write for my problem as it is a complete mess which makes no sense. Sorry.
I've been using w3schools javascript cookies tutorial and have found many other examples on the internet for how to set, get and check cookies. But for my code, I'm completely stuck.
You can try it with this solution:
// When DOM has loaded trigger cookieCheck function
document.addEventListener('DOMContentLoaded', cookieCheck);
// Checks whether cookie is present and whether to execute cookiebar function or not
function cookieCheck() {
const cookies = getCookies();
if(cookies.CookieConsent) {
/**
* Do your stuff when cookie is set
**/
cookiebar();
} else {
/**
* Do your stuff when cookie is NOT set
**/
}
}
// Insert HTML for cookiebar notice and accept button into page
function cookiebar() {
/**
* Function for CookieBar insertion
**/
}
// Creates consent cookie
function createCookie(name, value) {
document.cookie = [name, value].join('=');
}
function getCookies() {
let cookies = {};
document.cookie.split(";").forEach((cookie) => {
cookie = cookie.trim().split("=");
let name = cookie[0];
let val = cookie[1];
cookies[name] = val;
});
return cookies;
}