Home > Mobile >  How do I display a modal only once per hour for each user?
How do I display a modal only once per hour for each user?

Time:02-12

I have a website that displays a model on index load. Currently it loads every single time you go to the index page. It gets very annoying to the users of the website. I was wondering if I can only display it once per hour per user? The website is located at wikiraces.com

<!-- MODAL FOR NEWS-->
<div id="div1" >

  <!-- Modal content -->
  <div >
    <span >&times;</span>
    </div>
    <!-- Modal content -->
<div >
  <div >
    <span >&times;</span>
    <h2>New Features/Updates</h2>
  </div>
  <div >
   <h4> <p>The Fewest Clicks Game is Back!</p> </h4> 
    <p>
    It was down for maintanece for 14 hours but finally it is back
    </p> 
  
    <h4> The Multiplayer host random page is here! </h4> 
    <p>
     You can now play multiplayer without the hassle of chosing your own start!
      <br> 
      <br>
      <a href="/html/about.html"> <b> Report bugs </b></a>

    </p>
  </div>
  <div >
   <h5> Enjoy, and remember to share this website with your friends! </h5>
  </div>
</div>
  </div>

</div> 

<script>
  // Get the modal
var modal = document.getElementById("div1");

// Get the <span> element that closes the modal
var spanTimed = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
window.onload = function() {
  modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
spanTimed.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none"; 
  }
}

</script>

CodePudding user response:

We can store the last time the modal was opened in localStorage and everytime the user visits the site, we can check the difference between the time stored and the current time. If the time spend is greater than one hour, then show the modal.

window.addEventListener('load', () => {
  let time = localStorage.getItem('time');
  if ( time === null ) {
    localStorage.setItem('time', new Date());
    modal.style.display = "block";
    return;
  }
  
  let current = new Date();
  if ( current - time >= 60 * 60 * 1000 ) {
    modal.style.display = "block";
  }
 
})
  • Related