Recipe 13.2

Creating a Confirmation Dialog

This example shows a confirmation dialog with Confirm and Cancel buttons. When either of these buttons are clicked, it sets the dialog’s return value and closes it.

Demo

Confirm

Are you sure you want to do that?

Code

JavaScript
const dialog = document.querySelector('#confirm');
const trigger = document.querySelector('#show-confirm');
const result = document.querySelector('#result');
const confirmButton = document.querySelector('.confirm-button');
const cancelButton = document.querySelector('.cancel-button');

trigger.addEventListener('click', () => {
  dialog.showModal();
});

confirmButton.addEventListener('click', () => {
  dialog.close('confirm');
});

cancelButton.addEventListener('click', () => {
  dialog.close('cancel');
});

dialog.addEventListener('cancel', () => {
  dialog.returnValue = 'cancel';
});

dialog.addEventListener('close', event => {
  console.log(dialog.returnValue);
  if (dialog.returnValue === 'confirm') {
    result.textContent = '✅ User confirmed.';
  } else {
    result.textContent = '❌ User canceled.';
  }
});
HTML
<dialog id="confirm">
  <h2>Confirm</h2>
  <p>Are you sure you want to do that?</p>

  <button type="button" class="btn btn-primary confirm-button">Confirm</button>
  <button type="button" class="btn btn-secondary cancel-button">Cancel</button>
</dialog>

<button type="button" id="show-confirm" class="btn btn-primary">Show Confirmation</button>

<div id="result"></div>
Web API Cookbook
Joe Attardi