skip to Main Content

I implemented a functionality of JS show Modal() and I want to close it when someone click outside the popup means on document.

2

Answers


  1. Below is a work demo, you can refer to it:

      <!-- pop-up dialog box, containing a form -->
    <dialog id="favDialog">
        <form method="dialog">
            <p>
                <label for="favAnimal">Favorite animal:</label>
                <select id="favAnimal" name="favAnimal">
                    <option></option>
                    <option>Brine shrimp</option>
                    <option>Red panda</option>
                    <option>Spider monkey</option>
                </select>
            </p>
            <div>
                <button id="cancel" type="reset">Cancel</button>
                <button type="submit">Confirm</button>
            </div>
        </form>
    </dialog>
    
    <div>
        <button id="updateDetails">Update details</button>
    </div>
    
    <script>
        const updateButton = document.getElementById("updateDetails");
        const cancelButton = document.getElementById("cancel");
        const dialog = document.getElementById("favDialog");
        dialog.returnValue = "favAnimal";
    
        function openCheck(dialog) {
            if (dialog.open) {
                console.log("Dialog open");
            } else {
                console.log("Dialog closed");
            }
        }
    
        // Update button opens a modal dialog
        updateButton.addEventListener("click", () => {
            dialog.showModal();
            openCheck(dialog);
        });
    
        // Form cancel button closes the dialog box
        cancelButton.addEventListener("click", () => {
            dialog.close("animalNotChosen");
            openCheck(dialog);
        });
     //close showModal() when someone click outside
        window.onclick = function (event) {
            if (event.target == dialog) {
                dialog.close("animalNotChosen");
                openCheck(dialog);
            }}
    </script> 
    

    result:
    enter image description here

    Login or Signup to reply.
  2. You can 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.

    <button onclick="this.nextElementSibling.showModal()">Open Dialog</button>
    
    <dialog style="padding: 0" onclick="event.target==this && this.close()">
      <form style="margin: 0; padding: 1rem">
        <p>Clicking the inner area doesn't close the dialog</p>
      </form>
    </dialog>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search