Reputation: 936
See this code:
https://www.w3schools.com/code/tryit.asp?filename=FFFP03OMYA94
I've got two buttons (or even more). When I click on the first button, it should display the first div. When I click on the second button, it should display the other div. This is only a snippet of my problem. I want to achieve, that when I click on a button, then it should open the div with the passed ID. Normally I have an unique ID, so I could also save the ID like this:
<div id="myModal+${person.id}" class="modal">
My problem is: How can I pass the ID to my javaScript and open the specific div for the passed ID?
Upvotes: 0
Views: 440
Reputation: 25634
You can store this ID in a data-*
attribute, like this:
// Here, I used a class for the buttons, since there are multiple ones
var btns = document.getElementsByClassName('myBtn'),
// These variables will hold the currently open modal and close button
modal, closeBtn;
// For each button
for(var i=0; i<btns.length; i++) {
// On click
btns[i].addEventListener('click', function(){
// Get the modal ID
var modalId = this.getAttribute('data-modal');
// Retrieve the corresponding modal
modal = document.getElementById(modalId);
// Retrieve the close button
closeBtn = modal.querySelector('.close');
// Show the modal
modal.style.display = "block";
}, false);
}
window.addEventListener('click', function(event) {
// If we clicked on the backdrop or the close button
if (event.target == modal || event.target == closeBtn) {
// Hide the modal
modal.style.display = "none";
}
}, false);
.modal{display:none;position:fixed;z-index:1;padding-top:100px;left:0;top:0;width:100%;height:100%;overflow:auto;background-color:#000;background-color:rgba(0,0,0,.4)}.modal-content{background-color:#fefefe;margin:auto;padding:20px;border:1px solid #888;width:80%}.close{color:#aaa;float:right;font-size:28px;font-weight:700}.close:focus,.close:hover{color:#000;text-decoration:none;cursor:pointer}
<h2>Modal Example</h2>
<button class="myBtn" data-modal="myModalA">Open Modal A</button>
<div id="myModalA" class="modal"><div class="modal-content"><span class="close">×</span><p>This is myModalA</p></div></div>
<button class="myBtn" data-modal="myModalB">Open Modal B</button>
<div id="myModalB" class="modal"><div class="modal-content"><span class="close">×</span><p>This is myModalB</p></div></div>
<button class="myBtn" data-modal="myModalC">Open Modal C</button>
<div id="myModalC" class="modal"><div class="modal-content"><span class="close">×</span><p>This is myModalC</p></div></div>
<button class="myBtn" data-modal="myModalD">Open Modal D</button>
<div id="myModalD" class="modal"><div class="modal-content"><span class="close">×</span><p>This is myModalD</p></div></div>
Upvotes: 1