Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading