简体   繁体   中英

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

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" class="modal fade" style="padding-top:30%;"> <div class="modal-dialog"> My Content of pop up is here. </div> </div>

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

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);
 }
});

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)
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM