kulan
kulan

Reputation: 1391

Multiple modals won't close when clicked outside of it

I followed this tut here: https://www.w3schools.com/howto/howto_css_modals.asp The problem is when I create two such modals, the first one won't close when I click outside of it. Here's the jsfiddle: https://jsfiddle.net/j1smeu3c/

// Get the modal
var modal1 = document.getElementById('myModal1');

// Get the button that opens the modal
var btn1 = document.getElementById("myBtn1");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn1.onclick = function() {
    modal1.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal1.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal1) {
        modal1.style.display = "none";
    }
}

//////////////////////////

// Get the modal
var modal2 = document.getElementById('myModal2');

// Get the button that opens the modal
var btn2 = document.getElementById("myBtn2");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[1];

// When the user clicks the button, open the modal 
btn2.onclick = function() {
    modal2.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal2.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal2) {
        modal2.style.display = "none";
    }
}

Upvotes: 1

Views: 1179

Answers (2)

Nedim Hozić
Nedim Hozić

Reputation: 1901

You have two window.onclick functions. Delete one of them and make one like this:

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

Upvotes: 0

Brian
Brian

Reputation: 1893

Your second declaration of window.onclick overwrites the first one. You should set both checks in one function.

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

}

Upvotes: 3

Related Questions