I didn't find any built in solution or workaround for closing the html5 <dialog>
element by clicking on its background(::backdrop
), although it's clearly a basic functionality.
Backdrop clicks can be detected using the dialog bounding rect.
var dialog = document.getElementsByTagName('dialog')[0];
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();
}
});
<dialog>
<p>Greetings, one and all!</p>
<form method="dialog">
<button>OK</button>
</form>
</dialog>