HackYa HackYa - 6 months ago 34
Javascript Question

Can't close modal box by clicking outside of the modal

I have modal boxes that I open this way.

<div class="modal-open" data-modal="modal-window-one">Modal1</div>

var btn = document.getElementsByClassName("modal-open");
for (var i = 0; i < btn.length; i++) {
var thisBtn = btn[i];
thisBtn.addEventListener("click", function(){
var modal = document.getElementById(this.dataset.modal);

modal.className = "modal-reveal";
}, false);

And I am trying to have this modal close by clicking anywhere outside of this modal which has opened.

Here is my code.

window.addEventListener('mouseup', function(event){
var box = document.getElementsByClassName('modal-reveal');
if (event.target != box && event.target.parentNode != box){
box.className = "modal-hidden";

What am I doing wrong here? No console error & I can't figure out why this code won't work.

Here is my fiddle: https://jsfiddle.net/mspsys/z46woxv0/


You should change this line:

var box = document.getElementsByClassName('modal-reveal');

to something like:

var box = document.getElementsByClassName('modal-reveal')[0];

.getElementsByClassName returns HTMLCollection. You need to get one element.