Multiple Modals One Script
by UltimateNoob
HTML
<a id="btnB12" class="modal-btn" data-modal-id="B12" href="#">B12</a>
<a id="btnB02" class="modal-btn" data-modal-id="B02" href="#">B02</a>
<!-- single modal -->
<div class="modal" id="myModal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<h2 class="modal-header"></h2>
<p class="modal-body"></p>
</div>
</div>
CSS
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
button {
cursor: pointer;
}
}
JavaScript
var modal = document.getElementById('myModal');
var modalData = {
"B12": {
"header":"Modal B12",
"body":"Here's the text for Modal B12"
},
"B02": {
"header":"Modal B02",
"body":"Here's the text for Modal B02"
}
}
//open modal
$('.modal-btn').on('click', function(e) {
e.preventDefault();
var modalId = $(e.currentTarget).data('modal-id');
$('.modal-header').text(modalData[modalId].header);
$('.modal-body').text(modalData[modalId].body);
$('.modal').show();
});
//close modal
$('.close').on('click', function(e){
$('.modal').hide();
});
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}