I'm using a modal to display a image-slider for different references of my website. This is how my references look like:
<div>
<a id="openmodal">
<p>Project 1</p>
</a>
</div>
<div>
<a id="openmodal">
<p>Project 2</p>
</a>
</div>
<div>
<a id="openmodal">
<p>Project 3</p>
</a>
</div>
This is the structure of my modal(s)
<div id="modal1" class="modal">
<div class="modal-content">
<p>Title</p>
<div class="slideshow-container">
<img src="image1.jpg">
<img src="image2.jpg">
<img src="image3.jpg">
<button class="prev" onclick="plusSlider(-1)">❮</button>
<button class="next" onclick="plusSlider(1)">❯</button>
</div>
</div>
</div>
<div id="modal2" class="modal">
<div class="modal-content">
<p>Title</p>
<div class="slideshow-container">
<img src="image1.jpg">
<img src="image2.jpg">
<img src="image3.jpg">
<button class="prev" onclick="plusSlider(-1)">❮</button>
<button class="next" onclick="plusSlider(1)">❯</button>
</div>
</div>
</div>
<div id="modal3" class="modal">
<div class="modal-content">
<p>Title</p>
<div class="slideshow-container">
<img src="image1.jpg">
<img src="image2.jpg">
<img src="image3.jpg">
<button class="prev" onclick="plusSlider(-1)">❮</button>
<button class="next" onclick="plusSlider(1)">❯</button>
</div>
</div>
</div>
The JS looks like this:
var modal = document.getElementById("modal1");
var btn = document.getElementById("openmodal");
btn.onclick = function() {
modal.style.display = "block";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
Unfortunately don't know how to modify the JS if i want use more than one modal (with the id="modal2" and id="modal3" ...) on a html page. Or how can i use each modal for each project? Maybe someone can help me?
Thanks so much!
First of all you are using the same id on all the anchor tags which is wrong. You should only have one id per page. You can instead add a common class and add event listeners on them.
Here in the below code we have added class
openmodalfor all the anchor links and addeddata-idattribute to differentiate them. On button click we just get this id and open the modal dynamically. This way it will work even if you plan to add more modals to the page.You can try out something like below.