Modal window

vancouver·2023년 5월 27일
0

javascript이해하기

목록 보기
12/22
post-custom-banner

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <title>Modal window</title>
  </head>
  <body>
    <button class="show-modal">Show modal 1</button>
    <button class="show-modal">Show modal 2</button>
    <button class="show-modal">Show modal 3</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>

    <script src="script.js"></script>
  </body>
</html>

javascript

"use strict";

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

const openModal = function () {
  modal.classList.remove(`hidden`); // 클래스의 정의된`hidden`을 제거
  overlay.classList.remove(`hidden`);// 클래스의 정의된`hidden`을 제거
};

const closeModal = function () {
  modal.classList.add(`hidden`);// 클래스의 정의된`hidden`을 추가
  overlay.classList.add(`hidden`);// 클래스의 정의된`hidden`을 추가
};

for (let i = 0; i < btnOpenModal.length; i++)
  btnOpenModal[i].addEventListener(`click`, openModal);

btnCloseModal.addEventListener(`click`, closeModal);

overlay.addEventListener(`click`, closeModal);

document.addEventListener("keydown", function (event) {
  console.log(event.key);

  if (event.key === `Escape` && !modal.classList.contains(`hidden`)) {
    closeModal(); // `Escape`의 키를 눌렀을때 Modal window창 사라짐
  } else if (event.key === `1` && modal.classList.contains(`hidden`)) {
    openModal(); // `1`의 키를 눌렀을때 Modal window창 나타남
  }
});
post-custom-banner

0개의 댓글