Labs ICT
Pro Login

Dialog Element

2 min read | HTML Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

You know those popup windows that appear on top of a page asking you to confirm something or log in? Those are called dialogs. HTML has a built-in <dialog> element that gives you a proper, accessible modal dialog — no fancy library needed.

The Dialog Element

The <dialog> element is a native HTML element for creating dialogs. By default, a dialog is hidden. You use JavaScript to show it — either with show() for non-modal dialogs or showModal() for modal dialogs that block interaction with the rest of the page.


<dialog id="myDialog">
  <p>Are you sure you want to delete this item?</p>
  <button id="cancelBtn">Cancel</button>
  <button id="confirmBtn">Confirm</button>
</dialog>

<button id="openBtn">Delete Item</button>
    

showModal vs show

showModal() opens the dialog as a modal — it overlays the page content with a backdrop and traps focus inside the dialog. show() opens it as a non-modal dialog that sits on top of the page but still lets users interact with the rest of the content.


<script>
  const dialog = document.getElementById('myDialog');
  const openBtn = document.getElementById('openBtn');
  const cancelBtn = document.getElementById('cancelBtn');

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

  cancelBtn.addEventListener('click', () => {
    dialog.close();
  });
</script>
    

The Close Method and Return Value

You can close a dialog with dialog.close() and pass a return value. This is useful when you want to know which button the user clicked — like "confirm" or "cancel" — to decide what to do next.


<script>
  const confirmBtn = document.getElementById('confirmBtn');
  confirmBtn.addEventListener('click', () => {
    dialog.close('confirmed');
  });

  dialog.addEventListener('close', () => {
    if (dialog.returnValue === 'confirmed') {
      console.log('User confirmed the deletion');
    }
  });
</script>
    

Styling the Dialog and Backdrop

The dialog element comes with some default styles, but you can customize everything. The ::backdrop pseudo-element lets you style the dark overlay behind a modal dialog, and you can style the dialog box itself however you like.


<style>
  dialog {
    border: none;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  }
  dialog::backdrop {
    background-color: rgba(0, 0, 0, 0.5);
  }
</style>