I'm working on a simple modal that can be triggered by multiple buttons, but I need each button to load different content into the modal. Here are the links:
<a class="myBtn" href="#">Cats</a>
<a class="myBtn" href="#">Dogs</a>
and here are the content divs:
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close"><img src="svg/close.svg"></span>
<div class="modal-header clearfix">
<h3">Cats</h3>
</div>
<div class="modal-body">
<h4>Content for Cats goes here.</h4>
</div>
</div>
</div>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close"><img src="svg/close.svg"></span>
<div class="modal-header clearfix">
<h3">Dogs</h3>
</div>
<div class="modal-body">
<h4>Content for Dogs goes here.</h4>
</div>
</div>
</div>
Finally, here is the JS code:
<script type="text/javascript">
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.querySelectorAll(".myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
[].forEach.call(btn, function(el) {
// When the user clicks the button, open the modal
el.onclick = function() {
modal+'me'.style.display = "flex";
}
})
// 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";
}
}
</script>
If you have any suggestions on how to make the buttons unique so each one loads specific content into the modal, please share your solution. Thank you!