Post

dialog태그 활용하기

📌시작하며

react-portal에 대해 정리하다가 알게 된 dialog태그에 대해 정리해보고자 한다.

<dialog>태그

dialog 태그는 팝업 대화 상자를 간단하게 만들 수 있는 태그로, 경고창, 확인창 입력폼 등으로 활용할 수 있다. 기본적으로 모달 형태를 갖는다.

dialog태그는 어떤 브라우저에서 사용할 수 있을까? MDN에서는 다음과 같이 설명한다.

이 기능은 2022년 3월부터 최신 디바이스 및 브라우저 버전에서 작동합니다. 구형 디바이스나 브라우저에서는 이 기능이 작동하지 않을 수 있습니다.

can i use 사이트에서 찾아본 결과, 최신 버전의 브라우저에서 대부분 지원하고 있음을 확인했다.

✅기본 사용법

속성명설명
openbooelan 값을 이용해 dialog를 열고 닫는다.
close다이얼로그를 닫는다.
showModal모달 다이얼로그를 표시한다.
이때 모달 다이얼로그가 열린 경우, 사용자가 닫을 때 까지 다른 부분과 상호 작용할 수 없다.

✅예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>dialog 예제</title>
  </head>
  <body>
    <div>
      <p>메인화면입니다.</p>
      <button id="openBtn">모달 Open</button>
    </div>
    <dialog id="myModal">
      <p>모달입니다.</p>
      <button id="closeBtn">모달 Close</button>
    </dialog>
  </body>
</html>

위와 같이 html 구조를 잡고, JS를 이용해 제어해주면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
let modal = document.getElementById("myModal")
let openButton = document.getElementById("openBtn")
let closeButton = document.getElementById("closeBtn")

// 닫기 버튼 이벤트
closeButton.addEventListener("click", function () {
  modal.close() //모달 닫기
})

// 열기 버튼 이벤트
openButton.addEventListener("click", function () {
  modal.showModal() // 모달 열기
})

🗂️참고 사이트

  • https://developer.mozilla.org/ko/docs/Web/HTML/Element/dialog
This post is licensed under CC BY 4.0 by the author.