<dialog>란?HTML5에서 새롭게 추가된 <dialog> 태그는 모달 창이나 대화 상자를 구현하기 위한 요소입니다. 브라우저에서 기본적으로 모달 UI를 제공하며, 사용자와 상호 작용할 수 있는 대화 상자를 쉽게 만들 수 있도록 설계되었습니다.
이 태그는 자바스크립트의 showModal( ), close( ) 와 같은 내장 메서드와 함께 사용디어, 모달이나 비모달 대화 상자를 구현할 수 있습니다.
<dialog id="example-dialog">
<h2>Dialog Example</h2>
<p>This is a modal dialog.</p>
<form method="dialog">
<button>Close</button>
</form>
</dialog>
<button id="open-dialog">Open Dialog</button>
const dialog = document.getElementById('example-dialog');
const openButton = document.getElementById('open-dialog');
openButton.addEventListener('click', () => {
dialog.showModal(); // 모달 열기
});
dialog.addEventListener('close', () => {
console.log('Dialog closed!');
});
method="dialog"란?
- method="dialog"는
<form>태그에 사용되며, 버튼 클릭 시 상자를 자동으로 닫는 동작을 제공합니다.
<dialog> 내부에 포함된 <form> 태그에 설정해야 합니다.method="dialog"를 활용한 동작
<form> 태그에 method="dialog"를 추가합니다.
폼 내부에 버튼을 클릭하면 모달 창이 닫히고, close 이벤트가 트리거됩니다.
returnValue:
<dialog id="example-dialog">
<h2>Confirmation</h2>
<p>Are you sure you want to continue?</p>
<form method="dialog">
<button value="yes">Yes</button>
<button value="no">No</button>
</form>
</dialog>
<button id="open-dialog">Open Dialog</button>
<script>
const dialog = document.getElementById('example-dialog');
const button = document.getElementById('open-dialog');
// 모달 열기
button.addEventListener('click', () => dialog.showModal());
// 모달 닫힘 이벤트
dialog.addEventListener('close', () => {
console.log('User selected:', dialog.returnValue);
});
</script>
"Open Dialog" 버튼을 클릭하면 모달 창이 나옵니다.
모달 창에서 "Yes" or "No" 버튼을 클릭하면 모달이 닫히고, returnValue에 "yes" or "no" 값이 설정됩니다.
닫힐 때 close 이벤트가 실행되고, 선택된 값이 콘솔에 출력됩니다.
<dialog> 태그의 특징<dialog> 태그는 기본적으로 화면에 보이지 않습니다.
JavaScript를 통해 명시적으로 열어야 합니다.
모달 모드: 대화 상자가 활성화되면 화면의 나머지 부분과의 상호작용이 차단됩니다. (예: 게임 오버 화면)
비모달 모드: 대화 상자가 활성화되어도 화면의 나머지 부분과 상호작용할 수 있습니다. (예: nav바의 드롭다운 option)
<dialog>는 기본적으로 브라우저 스타일로 대화 상자처럼 표시됩니다.<dialog>가 열려 있는지 여부를 나타내는 속성.
open 속성이 존재하면 대화 상자가 화면에 표시됩니다.
예제:
<dialog open>
<p>This dialog is always open.</p>
</dialog>
1) show( )
<dialog>를 비모달(non-modal) 상태로 화면에 표시합니다.
비모달 상태에서는 대화 상자 외부와도 상호작용할 수 있습니다.
예제:
const dialog = document.querySelector('dialog');
dialog.show();
2) showModal( )
<dialog>를 모달(modal) 상태로 화면에 표시합니다.
모달 상태에서는 대화 상자 외부와의 상호작용이 차단됩니다.
const dialog = document.querySelector('dialog');
dialog.showModal();
3) close( )
<dialog>를 닫습니다.
모달이 닫힐 때, close 이벤트가 트리거됩니다.
예제:
const dialog = document.querySelector('dialog');
dialog.close();
4) returnValue
예제:
const dialog = document.querySelector('dialog');
dialog.showModal();
// 모달 닫기
dialog.close('user cancelled'); // returnValue가 'user cancelled'로 설정
console.log(dialog.returnValue); // 'user cancelled'