Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss html dialog element by clicking the backdrop

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?

like image 702
Explosion Pills Avatar asked Oct 13 '16 17:10

Explosion Pills


1 Answers

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>
like image 60
gaetanoM Avatar answered Oct 17 '22 06:10

gaetanoM