Tanasa Paul Tanasa Paul - 4 months ago 45
HTML Question

How to open modal with multiple buttons?

I have a modal and I want to open it with more than one button.

First button (in 'Diamont Packet') work, this open the modal, but the other buttons don't work. The ids of buttons are all named

id="detail"
.

How to make it work all the buttons, videlicet all the buttons to open the modal?

This is my full code https://jsfiddle.net/hxhjyhpv/1/.

This is my js code:

var modal = document.getElementById('modal');
var btn = document.getElementById("detail");
var span = document.getElementsByClassName("close")[0];

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

Answer

ID's should be unique on the page. Simply add some classes, and use document.querySelectorAll to fetch an array of buttons, and you're good to go.

See my updated jsfiddle here.

var modal = document.getElementById('modal');
var btns = document.querySelectorAll('.pack.detail'); 
var span = document.getElementsByClassName("close")[0];

[].forEach.call(btns, function(el) {
  el.onclick = function() {
      modal.style.display = "block";
  }
})
span.onclick = function() {
    modal.style.display = "none";
}
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
Comments