HTML Dialog
What Is It?
A dialog is a small window for a message or decision. JavaScript opens a modal dialog, which blocks interaction with the page behind it.
What the Tags Mean
dialog: the window.showModal(): opens it as a modal.form method="dialog": closes it on submission.aria-labelledby: connects the dialog to its heading.
Example 1
Save each example as index.html and open it in your browser. Each code block is a complete page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Dialog</title>
</head>
<body>
<button id="open" type="button">Show message</button>
<dialog id="message" aria-labelledby="message-title">
<h2 id="message-title">Hello!</h2>
<p>Welcome to the lesson.</p>
<form method="dialog"><button>Close</button></form>
</dialog>
<script>
document.getElementById("open").addEventListener("click", () => {
document.getElementById("message").showModal();
});
</script>
</body>
</html>Browser preview
What you see: Show message opens the dialog. Close dismisses it. The rest of the page cannot be used while it is open.
Example 2: Another Use
A visible dialog can also be non-modal. This one starts open and does not block the rest of the page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Dialog</title>
</head>
<body>
<dialog open>
<p>Your preview is ready.</p>
<form method="dialog"><button>Close</button></form>
</dialog>
</body>
</html>Browser preview
Simple Tip
Give readers a visible close button. Do not rely only on the Escape key.
Try It Yourself
Change the dialog message and test it with the keyboard.