DEV Community

Haruka Kakiuchi
Haruka Kakiuchi

Posted on • Edited on

Simple Modal with Javascript

This is a note that how to make a simple modal.

<button class="show-modal">Show modal </button>

<div class="modal hidden">
      <button class="close-modal">&times;</button>
      <h1>I'm a modal window</h1>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
        veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
        commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
        velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
        occaecat cupidatat non proident, sunt in culpa qui officia deserunt
        mollit anim id est laborum.
      </p>
    </div>
    <div class="overlay hidden"></div>

Enter fullscreen mode Exit fullscreen mode
.hidden {
  display: none;
}

.modal {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 70%;
  background-color: #fff;
  padding: 6rem;
  border-radius: 8px;
  box-shadow: 0 3rem 5rem rgb(0 0 0 /.3);
  z-index: 99;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgb(0 0 0 /.6);
  backdrop-filter: blur(4px);
  z-index: 1;
}

Enter fullscreen mode Exit fullscreen mode
'use strict';

const modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');
const btnCloseModal = document.querySelector('.close-modal');
const btnOpenModal = document.querySelectorAll('.show-modal');

const closeModal = function() {
  modal.classList.add('hidden');
  overlay.classList.add('hidden')
}

const openModal = function() {
  modal.classList.remove('hidden');
  overlay.classList.remove('hidden')
}

// if there are many open buttons
for (let i = 0; i < btnOpenModal.length; i++) {
  btnOpenModal[i].addEventListener("click", openModal);
}


btnCloseModal.addEventListener("click", closeModal);
overlay.addEventListener('click', closeModal);

// keyboard operation (Escape version)
document.addEventListener('keydown', function(e) {
  if(e.key === 'Escape' && !modal.classList.contains('hidden')) {
      closeModal();
  }
})


Enter fullscreen mode Exit fullscreen mode

for -> forEach

// if there are many open buttons
for (let i = 0; i < btnOpenModal.length; i++) {
  btnOpenModal[i].addEventListener("click", openModal);
}
Enter fullscreen mode Exit fullscreen mode


btnOpenModal.forEach(btn => btn.addEventListner('click', openModal)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)