I have a web page that is displaying a set of images using a table for simple layout. What I'd like to do is allow a user to click the image and have that image appear magnified in a modal.
The html row holding a graphic:
<tr>
<td>Graphic One</td>
<td><img class="graph" src="/chart1.jpg">
<div class="modal">
<div class="modal-content">
<span class="close-btn">×</span>
<img src="/chart1.jpg">
</div>
</div>
</td>
</tr>
This is repeated to create more rows with graphics. Here's the script:
<script>
let modalBtn = document.querySelector(".graph")
let modal = document.querySelector(".modal")
let closeBtn = document.querySelector(".close-btn")
modalBtn.onclick = function(){
modal.style.display = "block"
}
closeBtn.onclick = function(){
modal.style.display = "none"
}
window.onclick = function(e){
if(e.target == modal){
modal.style.display = "none"
}
}
</script>
This only seems to activate the first graphic on the page, though, so I'm assuming that the querySelector() stops at the first instance found.
How can I apply this to every row with an image in the table?
.querySelector()will return the first matching element. Try using.querySelectorAll()to return all matching elements then loop through them as needed. MDN docs