Search code examples
javascriptdialog

close html5 dialog by clicking outside of it


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?


Solution

  • EDIT: As of April 9th, 2024, the dialog element has support in all major browsers from versions released in 2022 and onwards. In other words, it is very safe to use now. Source: https://caniuse.com/?search=dialog

    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();
        }
    });