javascripthtmlmodal-dialog

How to detect if any modal <dialog> is open?


I have a page with multiple <dialog> elements, which I open as modal using their showModal() methods.

I want to detect whether any of them is currently opened from Javascript (since some event handlers shouldn't trigger when a modal is opened). Is it possible to check if modal is currently opened? Maybe through existance of dialog::backdrop or checking someway for inertness of non-modal content?


Solution

  • When dialog is opened as modal, it gets CSS pseudo-class :modal - so it can be queried with selector:

    document.querySelector("dialog:modal") === null; // No dialog is opened as modal.
    document.querySelector("dialog:modal") !== null; // Some dialog is opened as modal.