Blog>
Snippets

Timeout-Triggered Modal

Open a modal after a certain amount of time has passed on the page, useful for capturing user attention or delivering timed information.
<!-- HTML structure for the modal -->
<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Timeout-Triggered Modal...</p>
  </div>
</div>
This is the HTML markup for the modal. It has a modal-content div that contains the content of the modal, and a close button represented by a span with a times character.
/* CSS for the modal */
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
This is the CSS that styles the modal. The modal starts as `display: none;` and becomes visible when activated. The .modal-content div is centered on the page and styled to look like a modal window. The .close class is styled to represent a close button.
// JavaScript to open the modal after a set time

// When the user loads the page, wait for 3 seconds before showing the modal
window.onload = function() {
  setTimeout(function() {
    document.getElementById('myModal').style.display = 'block';
  }, 3000); // Timeout set for 3 seconds (3000 milliseconds)
};

// When the user clicks on <span> (x), close the modal
var span = document.getElementsByClassName('close')[0];
span.onclick = function() {
  var modal = document.getElementById('myModal');
  modal.style.display = 'none';
};
This JavaScript sets a timeout of 3 seconds when the page is loaded to display the modal by changing its display style from 'none' to 'block'. It also adds an event listener on the close button of the modal, which, when clicked, hides the modal.