1

Using the HTML 5.2 native <dialog> element I can open the dialog using Javascript.

document.addEventListener('DOMContentLoaded', () => {
  const dialog = document.getElementsByTagName('dialog')[0];
  dialog.showModal();
});

How can I use Javascript to close the dialog?

CloudBranch
  • 1,434
  • 3
  • 18
  • 23
  • 1
    [documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/showModal) suggests `.close()` - read it and see if I'm right – Jaromanda X Sep 25 '19 at 23:53
  • 1
    The example on the [`showModal`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/showModal) page clearly shows using `.close()` to close it. What's the problem? – Barmar Sep 25 '19 at 23:55
  • The downside to using those methods is the CSS pseudo-element ::backdrop won't work. – CloudBranch Sep 26 '19 at 00:00

1 Answers1

1

The dialog can be opened, and closed using the open() and close() methods. The downside to using these methods is the CSS pseudo-element ::backdrop won't work.

<button id="open">Open Dialog</button>
<button id="close">Close Dialog</button>

<dialog id="dialog">
  <h2>Dialog Title</h2>
  <p>Dialog content and other stuff will go here</p>
</dialog>

<script>
const dialog = document.getElementById("dialog");

document.getElementById("open").addEventListener("click", () => {
  dialog.show();
});

document.getElementById("close").addEventListener("click", () => {
  dialog.close();
});
</script>
CloudBranch
  • 1,434
  • 3
  • 18
  • 23