Search code examples
javascriptjquerycookiesjekyllexpired-cookies

How to make announcement banner cookie expire after specific time?


I want to make my announcement banner expire after 14 days. How would I have to change the following code to make that work?

//  Announcement Banner
var button = document.querySelector("button");
var element = document.querySelector("div");
var body = document.querySelector("body");

document
.getElementById("top-site-message-hide")
.addEventListener("click", function() {
    element.classList.toggle("yay");
    button.classList.toggle("yay");
    body.classList.toggle("yay");
    document.cookie =
    "cookie2=cocoMessageHide; expires=Fri, 3 Aug 2050 20:47:11 UTC; path=/";
});

if (document.cookie.indexOf("cookie2=") >= 0) {
    document.getElementById("top-site-message-wrapper").style.display = "none";
    body.style.paddingTop = "0px";
}

I tried a lot of different solutions. I think there would have to be a line that replaces the following line:

document.cookie =
"cookie2=cocoMessageHide; expires=Fri, 3 Aug 2050 20:47:11 UTC; path=/";

But I am not yet really experienced in JavaScript and JQuery.


Solution

  • You could use Date() combined with setDate() and getDate() to calcutate the currentDate + 14 days and then insert it into the expires part of your cookie.

    //  Announcement Banner
    var button = document.querySelector("button");
    var element = document.querySelector("div");
    var body = document.querySelector("body");
    
    document.getElementById("top-site-message-hide").addEventListener("click", function() {
      element.classList.toggle("yay");
      button.classList.toggle("yay");
      body.classList.toggle("yay");
    
      // Calculate date 14 days from now
      var expiryDate = new Date();
      expiryDate.setDate(expiryDate.getDate() + 14);
    
      // Set the cookie with the new expiry date
      document.cookie =
        "cookie2=cocoMessageHide; expires=" + expiryDate.toUTCString() + "; path=/";
    });
    
    if (document.cookie.indexOf("cookie2=") >= 0) {
      document.getElementById("top-site-message-wrapper").style.display = "none";
      body.style.paddingTop = "0px";
    }