HTML <dialog> Tag โ Popup / Modal Box
๐ Introduction
The <dialog> tag is used to create a popup window (modal dialog).
It can be:
- Shown or hidden using JavaScript
- Used for alerts, forms, confirmations
- Modern replacement for simple popup UI
๐งฑ Syntax
<dialog open>This is a dialog box</dialog>
๐ก Example (Basic Dialog)
<!DOCTYPE html>
<html>
<head>
<title>Dialog Example</title>
</head>
<body>
<h2>Dialog Box Example</h2>
<dialog id="myDialog">
<p>Hello! This is a popup dialog.</p>
<button onclick="document.getElementById('myDialog').close()">
Close
</button>
</dialog>
<button onclick="document.getElementById('myDialog').showModal()">
Open Dialog
</button>
</body>
</html>
๐ฅ๏ธ Output Explanation
- Dialog is hidden by default
- Clicking "Open Dialog" shows it
- Clicking "Close" hides it
๐ฏ Important Methods
1. show()
dialog.show();
โ Opens dialog (non-modal)
2. showModal()
dialog.showModal();
โ Opens dialog with background locked (modal)
3. close()
dialog.close();
โ Closes the dialog
๐ง Important Concept
๐ <dialog> is a native popup system in HTML
| Feature | Dialog |
|---|---|
| Built-in popup | โ |
| Needs JavaScript | โ (for control) |
| Modern UI support | โ |
๐งฉ Example (Login Popup)
<dialog id="login">
<h3>Login</h3>
<input type="text" placeholder="Username" /><br /><br />
<input type="password" placeholder="Password" /><br /><br />
<button onclick="login.close()">Close</button>
</dialog>
<button onclick="login.showModal()">Open Login</button>
๐จ Styling Example
dialog { padding: 20px; border: none; border-radius: 10px; }
โ๏ธ <dialog> vs Old Alerts
| Feature | <dialog> |
alert() |
|---|---|---|
| Custom UI | โ | โ |
| Styling | โ | โ |
| Modern apps | โ | โ |
๐ซ Common Mistakes
- Forgetting
showModal()โ - Not adding close button โ
- Using it without JavaScript โ
๐งช Mini Exercise
Create a page with:
- A button to open a dialog
- A dialog with a message
- A close button inside dialog
- Style the dialog box