0

I have 2 pop-up modals in a webpage which i want to close if the user clicks anywhere outside the modal. The problem is only the 2nd one works 1st doesn't.

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

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

3 Answers3

0

You are overriding the first onclick with the second one.

And just one onclick on the window that checks the modal type and base on that you set it display none.

  • I know that i am overriding the code. But i have 2 variables modal1 and modal2, how else am i supposed to close both the modals ? Could you provide a code snippet ? – Rishi Kabra Feb 13 '17 at 04:38
0

Use the same on-click function for both pop-up modals.

window.onclick = function(event){
if (event.target == modal1)    
{ modal1.style.display = "none"; }
if (event.target == modal2)
{ modal2.style.display = "none"; }
} 
Aditya
  • 110
  • 1
  • 8
0

You are overriding the first onclick with the second one.You can do like this;

window.onclick = function(event){
 if (event.target == modal1){modal1.style.display = "none"; } 
 if (event.target == modal2){modal2.style.display = "none";}
}
shangzhouwan
  • 246
  • 1
  • 6