1

My modal popups close when the close button in the modal itself is clicked, but I want them to close when users click anywhere in the window. I've got this javascript in there so far:

    var span = document.getElementsByClassName("close");
var btn = document.getElementsByClassName("click-to-open");
var modal=document.getElementById("modal-window-4");

for (var i = 0; i < btn.length; i++) {
  var thisBtn = btn[i];
      thisBtn.addEventListener("click", function(){
        var modal = document.getElementById(this.dataset.modal);
        modal.style.display = "block";
    }, false);

}

for (var j = 0; j < span.length; j++) {
  var closeThis = span[j];
      closeThis.addEventListener("click", function(){
        var closeModal = document.getElementById(this.dataset.modal);
        closeModal.style.display = "none";
    }, false);
}



window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

Codepen here: http://codepen.io/FelixB/pen/QyOpoo

Other posts here deal with jQuery, but I've already got this going in straight-up javascript, so I'm hoping someone knows of a simple way to achieve this.

Felix B
  • 147
  • 1
  • 3
  • 13

1 Answers1

0

I used the body onload event to initialized the rest of the event handlers. I set the click handler once the panel is visible. It seems to work ok for me.

                function init() {
                    var span = document.getElementsByClassName("close");
                    var btn = document.getElementsByClassName("click-to-open");
                    var modal = document.getElementById("modal-window-4");

                    for (var i = 0; i < btn.length; i++) {
                        var thisBtn = btn[i];
                        thisBtn.addEventListener("click", function () {
                            var modal = document.getElementById(this.dataset.modal);
                            modal.style.display = "block";
                            modal.addEventListener("click", function () { modal.style.display = "none"; modal.removeEventListener("click"); });
                        }, false);

                    }

                }

and html

      <body  onload="init()">
      <!-- and the rest of  your code -->
      </body>
Bindrid
  • 3,655
  • 2
  • 17
  • 18