Recipe 13.1

Creating an Alert Dialog

This example creates a simple alert dialog that shows a message and can be dismissed.

Demo

ℹ️ Alert

This is an alert dialog.

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>
Web API Cookbook
Joe Attardi