77

I didn't find any built in solution or workaround for closing the html5 <dialog> element by clicking on its background(::backdrop), although it's clearly a basic functionality.

12 Answers 12

61

Backdrop clicks can be detected using the dialog bounding rect.

var dialog = document.getElementsByTagName('dialog')[0];
dialog.showModal();
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();
  }
});
<dialog>
  <p>Greetings, one and all!</p>
  <form method="dialog">
    <button>OK</button>
  </form>
</dialog>

7
  • 7
    I had to also check that the event.target was the dialog. EG if (!isInDialog && event.target.tagName === 'DIALOG'). If a form is submitted within the dialog via hitting 'enter', then a click event event will bubble up from the submit button, and for some reason its clientX and clientY are 0.
    – kmurph79
    Dec 27, 2016 at 1:22
  • 1
    @kmurph79 Try my answer below - it negates the need to check the bounding client rectangle.
    – marksyzm
    Aug 30, 2019 at 15:31
  • 2
    Any reason for not using rect.right and rect.bottom instead of rect.left + rect.width and rect.top + rect.height? Jan 6, 2020 at 11:07
  • But!, you need to know, that any click by document.querySelector().click() can trigger doalog.close(). Just today faceup with this problem. Jan 13, 2023 at 11:42
  • 3
    feels super complicated for what it's doing.
    – Philll_t
    Jul 17, 2023 at 21:33
32

Another simple method similar to the wrapped div method mentioned by others is to give the dialog itself padding: 0 (as Chrome tends to give the dialog padding, for example) and add the click event to the dialog. The form element picks up the difference anyway so there's no need for an extra div. I've noticed the form wasn't used in any examples above so I thought this would be worth throwing in as it's part of the standard when working with buttons in a dialog.

function onClick(event) {
  if (event.target === dialog) {
    dialog.close();
  }
}

const dialog = document.querySelector("dialog");
dialog.addEventListener("click", onClick);
dialog.showModal();
form {
  max-width: 200px;
}
<button onclick="window.dialog.showModal()">Open dialog</button>

<dialog id="dialog" style="padding: 0; border: 0;">
  <form method="dialog">
    <div>Hello from dialog element. You can close me by clicking outside or Close button</div>
    <button>Close</button>
  </form>
</dialog>

Demo on CodePen

3
  • 1
    This will work with any element that covers the dialog box; good job including the spec-fulfilling form. Jul 18, 2020 at 20:33
  • 2
    A problem is that when the user for example selects something in the modal and moves his cursor outside of it. The onClick will trigger outside of the modal since the event is fired when the user releases the mouse. Jun 22, 2023 at 9:12
  • 1
    All solutions here suffer from the problem with drag-and-drop. I guess mouse events need to be used instead of click.
    – silverwind
    Jul 11, 2023 at 16:35
23
+50

You can't listen to click event on dialog ::backdrop by definition:

The showModal() method of the HTMLDialogElement interface displays the dialog as a modal, over the top of any other dialogs that might be present. It displays into the top layer, along with a ::backdrop pseudo-element. Interaction outside the dialog is blocked and the content outside it is rendered inert.

The semantically appropriate approach to close modal dialog by clicking outside is to inspect the event.target as suggested in this answer and implemented in this answer which can be simplified to

<button onclick="this.nextElementSibling.showModal()">Test</button>

<dialog style="padding: 0" onmousedown="event.target==this && this.close()">
  <form style="padding: 1rem" method="dialog">
    <p>Click outside to close the dialog.</p>
    <button>Click here</button>
  </form>
</dialog>

To prevent closing the form by clicking inside the element, holding down the click and then exiting the element before mouseup, onmousedown event is used instead of onclick, as @BritishWerewolf suggests in the comment.

To detect closing by clicking outside, use the returnValue parameter in the dialog close method and handle it in the close event. -1 magic number is used in the code below:

<dialog style="padding: 0"
  onmousedown="event.target==this && this.close(-1)"
  onclose="this.returnValue==-1 && alert('closed by clicking outside')"
>

2
  • 2
    +1 I did, however, change onclick="event/*...*/" to instead be an onmousedown to prevent clicking inside the element, holding down the click and then exiting the element before mouseup. It was closing when I was trying to highlight text if the mouse ended up outside the dialog. Nov 27, 2023 at 12:08
  • To add to this solution, I found scrollbars in the dialog content caused problems, at least on Desktop (not mobile, where scrollbars may be handled differently). A click on the scrollbar results in e.target being the same as if you click the backdrop, so the dialog closes. I found testing e.target.offsetWidth to be a useful metric, note also testing for negative in the following example: codepen.io/neekfenwick/pen/NWmvJMM
    – Neek
    Mar 28 at 9:25
17

Another more efficient solution is to wrap the dialog-content in a div with padding: 0. This way you can check for event.target of the click-event, which references the dialog in case of backdrop and any other element within the div in case of the actual modal.

By not checking the actual dimensions, we can prevent layout cycles.

0
13

The easiest way (no calculations, no dialog variables) is to directly compare if the clicked element is the same as the dialog, using event.currentTarget:

document.querySelector('dialog').addEventListener('mousedown', event => {
    if (event.target === event.currentTarget) {
        event.currentTarget.close()
    }
})

To avoid a click inside the dialog bounding box from also registering, the following CSS needs be set:

dialog {
    border:0;
    padding:0;
}

You may notice that, instead of onclick, mousedown is used.

This is for the usecase (mentioned by @BritishWerewolf, @Lars Flieger, and others) to avoid the dialog from closing when a user selects text (i.e. holds down the "click") but ends up outside the dialog.


Works the same for multiple dialogs:

document.querySelectorAll('dialog').forEach(element => 
    element.addEventListener('mousedown', 
        event => (event.target === event.currentTarget) && event.currentTarget.close()
    )
)
1
  • Be sure to set padding: 0 and border: 0, otherwise this will return true when clicking near the edges.
    – gkiely
    Jul 27, 2023 at 15:00
10

I figured out a very simple solution to this problem. Add a div container inside the <dialog>. Then check if that is the parent of the whole thing. If not, it's the dialog itself and it can be closed.

HTML

<dialog id="favDialog">
  <div class="test">
  Hello
  </div>
</dialog>

JS

document.querySelector('dialog').addEventListener('click', function(e) {
  if(!e.target.closest('div')) {
    e.target.close();
  }
});
2
  • This is a very good solution because it references the dialog itself instead of making me write other code that references by ID 150 X.
    – verlager
    Oct 3, 2021 at 2:39
  • 3
    Great solution. Note, however, that the dialog will also close when you click its padding, i.e. the area between the <dialog> border and the <div> (in my case 16px by default). One fix would be to set padding to zero for the <dialog> and add the padding to the <div> instead.
    – djvg
    Nov 7, 2022 at 8:22
4

For anyone stumbling upon this question and wants to follow the solution recommended by @meaku , here's how I solved it to use a to encapsulate the element and not work with getBoundingClientRect() calculation:

const popup = document.getElementById('popup');
const popupDialog = document.getElementById('popup-dialog');
popup.addEventListener('click', function(e){
  console.info(e.target.tagName);
  if (e.target.tagName === 'DIALOG') popupDialog.close()
});
<div id="popup" style="padding: 0">
    <dialog id="popup-dialog" style="display:none;">
        <h4>Dialog Title</h4>
        <footer class="modal-footer">
            <button id="popup-close" type="button">close</button>
            <button id="popup-ok" type="button">ok</button>
        </footer>
    </dialog>
</div>

1
1

If you use click it will close the dialog even if you drag from inside to outside the dialog, which can be annoying.

You can use pointerdown and pointerup to detect outside clicks more accurately.

// Close a dialog when the user clicks outside of it
// Not using click because form submit can trigger click on submit button,
// and also it would close if you drag from within the dialog to the outside
// (e.g. if you're selecting text, or perhaps you start clicking the close button and reconsider)
function clickOutsideToClose(dialog) {
    function isOutsideDialog(event) {
        const rect = dialog.getBoundingClientRect();
        return (
            event.clientX < rect.left ||
            event.clientX > rect.right ||
            event.clientY < rect.top ||
            event.clientY > rect.bottom
        );
    }
    addEventListener("pointerdown", function (event) {
        if (event.target !== dialog) {
            return;
        }
        if (isOutsideDialog(event)) {
            addEventListener("pointerup", function (event) {
                if (isOutsideDialog(event)) {
                    closeSettings();
                }
            }, { once: true });
        }
    });
}

I haven't tried the div content wrapper method so far. Maybe that also solves this problem, or can be made to solve it?

1

An even simpler version would be:

dialog.addEventListener('click', (ev) => {
    if (ev.offsetX < 0 || ev.offsetX > ev.target.offsetWidth ||
        ev.offsetY < 0 || ev.offsetY > ev.target.offsetHeight) {
            dialog.close();
    }
});
0
1

The following solution is rather simple and does not need any additional html structure:

const dialog = document.getElementById("myDialogId");
dialog.addEventListener("click", (event) => {
  if (event.target.nodeName === "DIALOG") {
    dialog.close();
  }
});

Found on Stefan Judis' blog

-1

A simplified version of @Seralo answer would be:

dialog.addEventListener("click", event => {
    const rect = dialog.getBoundingClientRect();
    if (event.clientY < rect.top || event.clientY > rect.bottom ||
        event.clientX < rect.left || event.clientX > rect.right) {
        dialog.close();
    }
};
-1

Full solution including preventing drag-clicks and clicking on nested elements from closing the dialog:

var button = document.querySelector('#btn');
var dialog = document.querySelector('#dialog');
var dialogInner = document.querySelector('#dialog-inner');

var lastMouseDownX = undefined;
var lastMouseDownY = undefined;
var lastMouseDownWasOutside = undefined;

button.addEventListener('click', (e) => {
dialog.showModal();
});

dialog.addEventListener('mousedown', (e) => {

  lastMouseDownX = e.offsetX;
  lastMouseDownY = e.offsetY;
  lastMouseDownWasOutside = !dialogInner.contains(e.target);
 });
  
dialog.addEventListener('click', (e) => {
  
  const wasDragAction = e.offsetX !== lastMouseDownX || e.offsetY !== lastMouseDownY;
  
  const isDragException = wasDragAction && !lastMouseDownWasOutside;

  if (!isDragException) {

if (e.target !== dialogInner  && !dialogInner.contains(e.target)) {
  dialog.close();
}
  }

  lastMouseDownX = undefined;
  lastMouseDownY = undefined;
  lastMouseDownWasOutside = undefined;
});
<dialog id="dialog" style="width: 500px; height: 500px; padding: 0;">
  <div id="dialog-inner" style="width: 100%; height: 100%; padding: 20px">My content
    <button type="button">a button inside</button>
  </div>
</dialog>

<button id="btn" type="button">
  Show modal
</button>

The trick is to use an inner container which share the same dimensions as the dialog, and then listening for clicks outside of it. Drag-clicks are handled by checking mouse position on mousedown event and comparing it to where the click actually happens.

Not the answer you're looking for? Browse other questions tagged or ask your own question.