Phil Phil - 1 month ago 6
HTML Question

Apply pop up to other buttons. Have code that works for one button

I have a function that allows me press a button and a pop up appears with the content I want. You can see this below. I want to have multiple of these but am not sure how to change the code. I would like to have different buttons that open different pop up contents.

I've copied and pasted the JS code and changed the relevant IDs but it doesn't work. Anyone have any ideas?

Thanks!!



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

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

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

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

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

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

HTML (Button):

<button class="buttin" id="myBtn">Terms & Conditions</button>

HTML (Pop Up Content):

<div id="myModal" class="modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<h3 style="margin-top: 0px;"><strong>Terms and Conditions</strong></h3>
Please read the following terms and conditions before using our website.
</div>
</div>




Answer

Like osyan said in the commen but you vill need a variable pr id. like:

var modal = document.getElementById('myModal1');
var modal2 = document.getElementById('myModal2');

See https://jsfiddle.net/3u8ummwn/2/ for a full example