Est. 2007
Turenki

Modal

Simple modal window that opens and closes smoothly. You can close it with Esc key, clicking outside the modal or with the close button.


HTML

<!-- Open -->    
<a href="#" class="OpenModal">Open modal</a>

<!-- Modal -->
<div class="Modal">
  <div class="ModalContent">
    <button title="Sulje" type="button" class="ModalClose">×</button>
    <h2>Modal</h2>
    <p>This is modal window.</p>
  </div>
</div>

JavaScript

document.addEventListener('DOMContentLoaded', function () {
  const modal = document.querySelector('.Modal');
  const content = document.querySelector('.ModalContent');
  const closeBtn = document.querySelector('.ModalClose');

  // Open modal
  function openModal() {
    modal.style.display = 'block';
    setTimeout(() => {
      modal.style.opacity = '1';
      content.style.opacity = '1';
      content.style.transform = 'scale(1) translate(-50%, -50%)';
    }, 10);
  }

  // Close modal
  function closeModal() {
    content.style.opacity = '0';
    content.style.transform = 'scale(0.98) translate(-50%, -50%)';
    setTimeout(() => {
      modal.style.opacity = '0';
      setTimeout(() => {
        modal.style.display = 'none';
        content.style.transform = 'scale(0.98) translate(-50%, -50%)';
      }, 500);
    }, 10);
  }

  // Open modal link    
  var openModalLink = document.querySelector(".OpenModal");
  openModalLink.addEventListener('click', function (event) {
      event.preventDefault(); 
      openModal();
  });

  // Close button
  closeBtn.addEventListener('click', () => {
    closeModal();
  });

  // Close modal when clicking outside
  window.addEventListener('click', (event) => {
    if (event.target === modal) {
      closeModal();
    }
  });

  // Close the modal with the Esc key
  document.addEventListener('keyup', (e) => {
    if (e.key === 'Escape') {
      closeModal();
    }
  });

  // Hide the modal 
  modal.style.display = 'none';
  modal.style.opacity = '0';
  content.style.transform = 'scale(0.98) translate(-50%, -50%)';
});

Styles

.Modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 10;
  transition: opacity 0.5s, display 0.5s; 
}   
   
.ModalContent {
  position: relative;
  top: 50%;
  left: 50%;
  background-color: #fff;
  padding: 1em;
  border-radius: 1em;
  max-width: 28em;
  width: calc(100% - 4em);
  opacity: 0;
  transition: opacity 0.5s, transform 0.5s;
}
      
.ModalClose{        
  user-select: none;
  cursor: pointer;
  border: 0;
  -webkit-appearance: none;
  outline: none;
  position: absolute;
  right: -1em;
  top: -1em;
  width: 3em;
  height: 3em;
  border-radius: 50%;
  transition-duration: 0.3s;
}

Blog articles

60°55’1.2”N
24°38’30.4”E