Blog>
Snippets

Cookie-Based Modal

Create a modal that only appears once per user by using cookies to track whether the modal has been closed, employing JavaScript for cookie management.
<!-- HTML for the modal -->
<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>
</div>
This is the HTML structure of the modal. It includes a container div with a class of 'modal', within which there is another div with a class 'modal-content' that holds the content of the modal. There is also a span with a class 'close' to provide an interactive closing element.
/* 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 for the modal. It sets up the style for the modal overlay background, the modal content area, and the close button, including hover and focus states for the button to enhance accessibility and user experience.
// JavaScript for Cookie-Based Modal functionality

document.onreadystatechange = function () {
  if (document.readyState === 'complete') {
    var modal = document.getElementById('myModal');
    var span = document.getElementsByClassName('close')[0];

    if(getCookie('modalShown') !== 'true') {
      modal.style.display = 'block';
    }

    span.onclick = function() {
      modal.style.display = 'none';
      setCookie('modalShown', 'true', 7);
    };
  }
};

function setCookie(name, value, days) {
  var expires = '';
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days*24*60*60*1000));
    expires = '; expires=' + date.toUTCString();
  }
  document.cookie = name + '=' + (value || '') + expires + '; path=/';
}

function getCookie(name) {
  var nameEQ = name + '=';
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
This JavaScript code begins by waiting for the document to be fully ready. It then gets the modal and close elements and checks if a cookie named 'modalShown' is set to 'true'. If not, it displays the modal. Clicking the close button hides the modal and sets a cookie 'modalShown' to 'true' for 7 days. The setCookie function creates or updates a cookie, and the getCookie function is used to retrieve the value of a cookie if it exists.