Search code examples
javascripthtmlmodal-dialogpopuppopupwindow

Popup after page loads opens only once per 24 hours


I have a working popup that opens after page is loaded.

I want it to be displayed once per 24 hours OR every time the user opens the browser OR any other way so it's not displayed after each page refresh etc.

I know it can be done using cookies, browser cache memory or php function. Could you provide any code to do it in the easiest possible way? Should I use database, cookies or some other way to store this data?

function PopUp(e){
  if(e == 'hide'){
    document.getElementById('outside').style.display='none';
  }else{
    document.getElementById('outside').removeAttribute('style');
  }
}

window.onload = function(){
  setTimeout(function(){
    PopUp('show');
  },25);
}
/*DEMO*/
#outside{position:fixed;top:0;left:0;bottom:0;right:0;background:rgba(100,50,0,.6)}
#inside{width:50%;height:50%;position:relative;top:20%;left:20%;background:#1C2338}
<div id="outside" style="display:none">
  <div id="inside">
    <h2 onClick="PopUp('hide')">CONTENT</h2>
  </div>
</div>


Solution

  • As mentioned in a comment, you can use a cookie with an expiry date to perform this action. Basically, just show the popup if a specific cookie doesn't exist, while setting the cookie with a 24-hour expiry time.

    if (document.cookie.indexOf("popupShown=true") == -1) {
        document.cookie = "popupShown=true; max-age=86400"; // 86400: seconds in a day
        // make the popup show here
    }
    

    After 24 hours, the cookie will expire, and on next webpage load the popup will be shown again.