Get the topmost dialog element?

Viewed 29

I'm using the latest HTML5 dialog element. And I use showModal to display multiple dialogs. So how do I get the topmost dialog element when multiple dialog elements are visible?

1 Answers

The dialog element does not seem to have this functionality built in. I think the only solution is to manually track your open dialogs.

Whenever a dialog is opened, append it to an array. The last item in the array will always be your active (topmost) dialog.

function show(dialog) {
  dialog.showModal();
  openDialogs.push(dialog);
  logTopDialog();
}

function close(dialog) {
  const i = openDialogs.indexOf(dialog);
  if (i !== -1) {
    openDialogs.splice(i, 1);
  }
  logTopDialog();
}

function logTopDialog() {
  console.log(`Top dialog = ${openDialogs.at(-1)?.id}`);
}

const openDialogs = [];

btn1.addEventListener('click', e => show(dialog1));
btn2.addEventListener('click', e => show(dialog2));
dialog1.addEventListener('close', _ => close(dialog1));
dialog2.addEventListener('close', e => close(dialog2));
<dialog id="dialog2">
  <form method="dialog">
    <p>Second dialog!</p>
    <button>Close</button>
  </form>
</dialog>

<dialog id="dialog1">
  <form method="dialog">
    <p>This is the first dialog here.</p>
    <button id="btn2" type="button">Open Dialog 2</button>
    <button>Close</button>
  </form>
</dialog>

<button id="btn1">Open Dialog 1</button>

Related