I am struggling to dynamically change the content of a modal based on different buttons being clicked. The issue lies in trying to reference the div
element within JavaScript since I can't have multiple elements with the same ID. As a newcomer to JS, this is quite confusing for me.
In its simplest form, I want each button to correspond with specific content in the modal; button 1 should open modal 1, and so on. I'm unsure about what modifications need to be made in my JS code to achieve this functionality.
Here is the link to the existing code.
<button id="modalbutton" class="modalbutton">Open Modal 1</button>
<button id="modalbutton" class="modalbutton">Open Modal 2</button>
<button id="modalbutton" class="modalbutton">Open Modal 3</button>
<!-- Content 1 -->
<div id="detailmodal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>1 Modal Header</h2>
</div>
<div class="modal-body">
<p>please link with 1</p>
<p>Some other text...</p>
</div>
<div class="modal-footer"><h3>Modal Footer</h3></div>
</div>
</div>
<!-- Content 2 -->
<div id="detailmodal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>2 Modal Header</h2>
</div>
<div class="modal-body">
<p>please link with 2</p>
<p>Some other text...</p>
</div>
<div class="modal-footer"><h3>Modal Footer</h3></div>
</div>
</div>
<!-- Content 3 -->
<div id="detailmodal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>3 Modal Header</h2>
</div>
<div class="modal-body">
<p>please link with 3</p>
<p>Some other text...</p>
</div>
<div class="modal-footer"><h3>Modal Footer</h3></div>
</div>
</div>
Script:
// Get the <span> element that closes the modal
var span = document.getElementsByClassName('close')[0];
// Open the modal when user clicks a button
for (let i = 0; i < btn.length; i++) {
btn[i].onclick = function() {
modal.style.display = 'block';
};
}
// Close the modal when <span> (x) is clicked
span.onclick = function() {
modal.style.display = 'none';
};
// Close the modal when user clicks outside of it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = 'none';
}
};