javascripthtmlcsscookiesbanner

How can I create a temporary banner with JavaScript?


I am new to this field and am currently building a website. I created a cookie banner with HTML and CSS. I need to know how can I make it start only once "every 24 hours for example" for each user.

I tried to use the IP address to distinguish the various users but I don't know how to memorize it.


Solution

  • To make your cookie banner display only once every 24 hours for each user, you can use browser cookies to store the user's consent information. Here's how you can implement it:

    When the user accepts the cookie banner, set a cookie in their browser with an expiration date of 24 hours from the current time.

    When the user visits your website, check if the cookie exists and if its expiration time has not yet passed. If the cookie exists and has not expired, do not display the cookie banner. Otherwise, display the banner.

        function setCookie(name, value, hours) {
      var expires = "";
      if (hours) {
        var date = new Date();
        date.setTime(date.getTime() + hours * 60 * 60 * 1000);
        expires = "; expires=" + date.toUTCString();
      }
      document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }
    
    function getCookie(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 showCookieBanner() {
      var cookieBanner = document.getElementById("cookie-banner");
      if (getCookie("cookieConsent") === null) {
        cookieBanner.style.display = "block";
      } else {
        cookieBanner.style.display = "none";
      }
    }
    
    function acceptCookies() {
      setCookie("cookieConsent", "true", 24);
      document.getElementById("cookie-banner").style.display = "none";
    }
    
    window.onload = function() {
      showCookieBanner();
    };