Skip to content Skip to sidebar Skip to footer

Can't Use Multiple Modal Popup

I want to use multiple modal popup, but when I write the code the second button can't work when I click on it. I use the code base on https://www.w3schools.com/howto/tryit.asp?fil

Solution 1:

Try something like this, although this will not work perfectly:

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

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

// 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";
}
btn2.onclick = function() {
  modal2.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal1.style.display = "none";
  modal2.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";
  }
  if (event.target == modal2) {
    modal2.style.display = "none";
  }
}
#myModal1,
#myModal2 {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myBtn1">1</button>
<div id="myModal1" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <div><img src="http://green-furniture.com.tw/cdn/cache_products/%e5%9c%b0%e4%b8%ad%e6%b5%b7-sm.png" id="pic" />
      <p id="title">ocean</p>
    </div>
  </div>
</div>

<button id="myBtn2">2</button>
<div id="myModal2" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <div><img src="" id="pic" />
      <p id="title"></p>
    </div>
  </div>
</div>

Post a Comment for "Can't Use Multiple Modal Popup"