I have implemented several html5 dialogs in a web page. I want to enable the user to click outside of the dialog in order to close it, instead of cluttering up the dialog with a close button or requiring an {escape} keypress. Many queries on this matter are for exotic js libraries but I want to use plain JS not jquery.
JS
// HALFHIDE
function openHALFHIDEdialog() {
var dialogHALFHIDEsource_O = document.getElementById("S-HALFHIDE");
dialogHALFHIDEsource_O.showModal();
}
function closeHALFHIDEdialog() {
var dialogHALFHIDEsource_C = document.getElementById("S-HALFHIDE");
dialogHALFHIDEsource_C.close(); }
HTML
<!-- S. HALFHIDE -->
<div class = "generic_dialog_container">
<dialog class = "generic dialog" id = "S-HALFHIDE">
<p>Blah blah blah</p>
</dialog></div>
<!-- END S HALFHIDE -->
How can I do this?
CodePudding user response:
This caused me to look into the dialog
element quite a bit. Just a forewarning, as I mentioned in my comments, the dialog
element is lacking in support as its not supported by Safari or Firefox.
Here is a REPL you can run that contains the solution: https://replit.com/@heyitsmarcus/Dialog#index.html
But, I did find a solution here that works here on Stack Overflow: How to close the new html <dialog> tag by clicking on its ::backdrop
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();
}
});