Recipe 13.1
Creating an Alert Dialog
Compatibility Note: Dialog
This feature may not be supported on all browsers yet. Please check the latest compatibility data before using in a production application.
Browser support for DialogThis example creates a simple alert dialog that shows a message and can be dismissed.
Demo
Code
JavaScript
const dialog = document.querySelector('#alert');
const okButton = document.querySelector('#ok-button');
const trigger = document.querySelector('#show-dialog');
okButton.addEventListener('click', () => {
dialog.close();
});
trigger.addEventListener('click', () => {
dialog.showModal();
});
HTML
<style>
#alert {
width: 350px;
}
</style>
<dialog id="alert">
<h2>ℹ️ Alert</h2>
<p>This is an alert dialog.</p>
<button
type="button"
id="ok-button"
class="btn btn-secondary"
>
OK
</button>
</dialog>
<button
type="button"
id="show-dialog"
class="btn btn-primary"
>
Show Dialog
</button>