Home > Software engineering >  How to bind my current Popup code in javascript to show the popup only once per day?
How to bind my current Popup code in javascript to show the popup only once per day?

Time:01-13

I am using below code to show a popup on my home page. But the problem is that it shows every time a user reloads the page. Instead of that I would like to be displayed once per day. Here is the code:

$(document).ready(function() {
  $("#myModal").modal('show');
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<div id="myModal"  style="padding-top:30%;">
  <div >
    My Content of pop up is here.
  </div>
</div>

I tried to bind it with cookie expiration but I couldn't do it.

CodePudding user response:

You can use the browser's local storage to store a timestamp when the modal was last shown.

Then, when the page loads, check the timestamp against the current date, if the date is different then display the modal otherwise do not display it.

Here's an example:

$(document).ready(function() {
 var lastShown = localStorage.getItem('modalShown');
 var currentDate = new Date().toDateString();

 if (lastShown !== currentDate) {
  $("#myModal").modal('show');
  localStorage.setItem('modalShown', currentDate);
 }
});

CodePudding user response:

you can do it like this

$(document).ready(function() {
  var todayCodeRecord = localStorage.getItem('today')
  var todayCode = new Date().toLocaleDateString()
  if(todayCodeRecord !== todayCode) {
    $("#myModal").modal('show');
    localStorage.setItem('today', todayCode)
  }
});
  • Related