Disable the html dialog element by clicking on the background

Using the lightweight library's construction material to create dialogs that essentially uses the main <dialog> , is there a way to dismiss the dialog by clicking on its background? (Direct clicking on the contents of the dialog box cannot be discarded).

 <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 a dialog is displayed corresponds to clicking on the dialog element, so it seems that there is no easy way to determine if the background has clicked ... is there a way to do this?

+5
source share
1 answer

You can use Element.getBoundingClientRect to get the size and position of the dialog and check 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> 
+2
source

Source: https://habr.com/ru/post/1258164/


All Articles