How to close the new html <dialog> tag by clicking on its ::backdrop How to close the new html <dialog> tag by clicking on its ::backdrop google-chrome google-chrome

How to close the new html <dialog> tag by clicking on its ::backdrop


Backdrop clicks can be detected using the dialog bounding rect.

var dialog = document.getElementByTagName('dialog');dialog.showModal();dialog.addEventListener('click', function (event) {    var rect = dialog.getBoundingClientRect();    var isInDialog=(rect.top <= event.clientY && event.clientY <= rect.top + rect.height      && rect.left <= event.clientX && event.clientX <= rect.left + rect.width);    if (!isInDialog) {        dialog.close();    }});


Another more efficient solution is to wrap the dialog-content in a div with padding: 0. This way you can check for event.target of the click-event, which references the dialog in case of backdrop and any other element within the div in case of the actual modal.

By not checking the actual dimensions, we can prevent layout cycles.


Another simple method similar to the wrapped div method mentioned by others is to give the dialog itself padding: 0 (as Chrome tends to give the dialog padding, for example) and add the click event to the dialog. The form element picks up the difference anyway so there's no need for an extra div. I've noticed the form wasn't used in any examples above so I thought this would be worth throwing in as it's part of the standard when working with buttons in a dialog.

<dialog style="padding: 0; border: 0;">  <form method="dialog">    <button>Click here</button>  </form></dialog><script>function onClick(event) {  if (event.target === dialog) {    dialog.close();  }}const dialog = document.querySelector("dialog");dialog.addEventListener("click", onClick);dialog.showModal();</script>

Demo on CodePen