Blog>
Snippets

Modal with Transitions

Enhance a basic modal by adding CSS transitions for smooth opening and closing animations, utilizing JavaScript to toggle classes.
<!-- HTML structure of a modal -->
<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close-btn">&times;</span>
    <p>Some text in the Modal..</p>
  </div>
</div>
This is the HTML markup for a basic modal. The modal has a container with a class 'modal' and a child 'modal-content' that contains the actual content of the modal. There is also a 'close' button represented by the '×' symbol.
/* CSS styles for the modal, including transitions */
.modal {
  display: none;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1;
}

.modal-content {
  margin: 15% auto;
  padding: 20px;
  width: 80%;
  transition: transform 0.3s ease-out;
}

.modal-show {
  display: block;
}

.modal-content-show {
  transform: scale(1);
}

.modal-content-hide {
  transform: scale(0);
}
This CSS provides styling for the modal and the modal content. It includes the 'modal-show' class to make the modal visible and 'modal-content-show' to apply a scaling transition for when the modal appears. 'modal-content-hide' applies a reverse transition effect for when the modal is closed.
// JavaScript to handle the modal transitions
const modal = document.getElementById('myModal');
const closeButton = document.querySelector('.close-btn');
closeButton.onclick = function() {
  modal.classList.toggle('modal-show', false);
  modal.querySelector('.modal-content').classList.add('modal-content-hide');
}

window.onclick = function(event) {
  if (event.target === modal) {
    modal.classList.toggle('modal-show', false);
    modal.querySelector('.modal-content').classList.add('modal-content-hide');
  }
}

function showModal() {
  modal.classList.toggle('modal-show', true);
  const content = modal.querySelector('.modal-content');
  content.classList.remove('modal-content-hide');
  content.classList.add('modal-content-show');
}
This JavaScript code selects the modal and close button elements. It defines the onclick event for the close button, where it toggles the display of the modal and applies the hide transition. It also checks if the window outside the modal has been clicked to close the modal. The `showModal` function toggles the modal visibility and applies the show transition.