Lucas
Lucas

Reputation: 165

HTML - Close pop up when clicking outside the div?

Got this script, but wondering what kind of function I need to add to make it close when clicking outside the box? Do I need to add another div and try to trigger that to make it close or?

Sorry I'm clueless considering writing javascript, I just understand how the events are created by the .onclick events but that's about it.

var closePopup = document.getElementById("popupclose");
        var overlay = document.getElementById("overlay");
        var popup = document.getElementById("popup");
        var button = document.getElementById("button");
        // Close Popup Event
        closePopup.onclick = function () {
            overlay.style.display = 'none';
            popup.style.display = 'none';
        };
        // Show Overlay and Popup
        button.onclick = function () {
            overlay.style.display = 'block';
            popup.style.display = 'block';
        }
#overlay {
            display: none;
            position: absolute;
            top: 0;
            bottom: 0;
            background: #99999945;
            width: 100%;
            height: 100%;
            opacity: 0.8;
            z-index: 100;
        }

        #popup {
            display: none;
            position: absolute;
            top: 25%;
            background: #fff;
            width: 80%;
            margin-left: 10%;
            z-index: 200;
            border-radius: 4px;
        }

        #popupclose {
            float: right;
            padding: 2px;
            cursor: pointer;
        }

        .popupcontent {
            padding: 10px;
        }

        #button {
            cursor: pointer;
        }
<button id="button" class="button btn--primary">Open div</button>

    <div id="overlay"></div>
    <div id="popup">
        <div class="popupcontrols">
            <span id="popupclose">Close X</span>
        </div>
        <div class="popupcontent">
            Content inside popup
        </div>
    </div>

Upvotes: 0

Views: 1492

Answers (1)

Fralle
Fralle

Reputation: 927

You could add a click-handler for the overlay element since that should cover all of the "outside" areas.

    overlay.onclick = function () {
        overlay.style.display = 'none';
        popup.style.display = 'none';
    };

Upvotes: 2

Related Questions