0

My code below is supposed to set a cookie with a 60 day expiration date when a button is clicked, which works Ok, but when I open the site in another window or refresh the page, the div still appears, I'm unable to find out why.

Can anyone stop what I have wrote wrong

(function () {
    "use strict";

    var cookieAlert = document.querySelector(".cookiealert");
    var acceptCookies = document.querySelector(".acceptcookies");

    cookieAlert.offsetHeight; // Force browser to trigger reflow (https://stackoverflow.com/a/39451131)

    if (!getCookie("acceptCookies")) {
       cookieAlert.classList.add("show");
    }

    acceptCookies.addEventListener("click", function () {
        setCookie("acceptCookies", true, 60);
        cookieAlert.classList.remove("show");
    });
})();

// Cookie functions stolen from w3schools
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 "";
}

Here is the HTML that I'm using

<div class="alert alert-dismissible text-center cookiealert show" role="alert">
    <div class="cookiealert-container">
        @privacyText <a href="@privacyLink">Learn more</a>

        <button id="btnCookiePolicy" type="button" class="btn btn-primary btn-sm acceptcookies" aria-label="Close">
            I agree
        </button>
    </div>
</div>
Paul Thompson
  • 113
  • 2
  • 12

1 Answers1

1

This is wrong...

<div class="alert alert-dismissible text-center cookiealert show" role="alert">

You need to remove the class show from the class list, as you want the dialog to be hidden by default, and then you add the show class if there is no cookie.

Just change that line to this...

<div class="alert alert-dismissible text-center cookiealert" role="alert">

That should solve your problem.

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67