Using the material design lite library to create dialogs, which essentially uses the underlying <dialog>
element, is there any way to dismiss the dialog by clicking on its backdrop? (When clicking the dialog contents themselves it should not be dismissed).
<dialog>Hi</dialog>
<button>show</button>
document.querySelector("button").addEventListener("click",
() => document.querySelector("dialog").showModal());
https://jsfiddle.net/fyjbvbqq/
Clicking anywhere on the screen when the dialog is shown corresponds to clicking the dialog
element so it seems like there is no simple way to determine if the backdrop was clicked ... is there a way to do this?
You might use the Element.getBoundingClientRect to get size and position of the dialog and test if the current client coordinates are inside this area:
document.querySelector("button").addEventListener("click", () => document.querySelector("dialog").showModal());
document.querySelector("dialog").addEventListener("click", (e) => {
var rect = e.target.getBoundingClientRect();
var minX = rect.left + e.target.clientLeft;
var minY = rect.top + e.target.clientTop;
if ((e.clientX < minX || e.clientX >= minX + e.target.clientWidth) ||
(e.clientY < minY || e.clientY >= minY + e.target.clientHeight)) {
e.target.close();
}
});
<dialog>Hi</dialog>
<button>
show
</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With