The goal here is to completely get rid of OnClick in HTML and execute everything in JS instead, preferably by using addEventListener
.
function ShowImage(imgs) {
var expandedImg = document.getElementById("expandedImg");
expandedImg.src = imgs.src;
expandedImg.parentElement.style.display = "block";
}
div.gallery img {
width: 100%;
height: auto;
}
.field {
padding: 3px 3px;
float: left;
width: 20%;
}
.expandedImg {
width: 75%;
margin: 0 auto;
}
.containerimage {
position: relative;
display: none;
text-align: center;
}
<div class="containerimage">
<!-- Expanded image -->
<img id="expandedImg">
</div>
<div class="field">
<div class="gallery">
<img src="https://wallpapercave.com/dwp1x/wp5539369.jpg" onclick="ShowImage(this);"> </div>
</div>
<div class="field">
<div class="gallery">
<img src="https://wallpapercave.com/dwp1x/wp5441501.jpg" onclick="ShowImage(this);">
</div>
</div>
<div class="field">
<div class="gallery">
<img src="https://wallpapercave.com/dwp1x/wp5405231.jpg" onclick="ShowImage(this);"> </div>
</div>
<div class="field">
<div class="gallery">
<img src="https://wallpapercave.com/dwp1x/wp4964086.png" onclick="ShowImage(this);"> </div>
</div>
Afterwards, I tried adding the following code in JS,
var galleryImages = document.querySelectorAll(".gallery img");
for (var image of galleryImages) {
image.addEventListener('click', ShowImage);
}
However, this only makes the clicked image appear for a split second and disappear, showing only the image icon instead.
5
Answers
I couldn’t understand too much from you code. But I hope It will help you and Next time please try to ask question with clean code.
To use
addEventListener
instead ofonClick
in theimg
tags, you can remove theonclick
attributes from the HTML code and useaddEventListener
to attach a click event to each image in your JavaScript code.Remove onclick attribute from tags and use this
El =Document.getElementsById("id name")
And
El.addEventListener("onclick", put your entire function here)
If i have undrestood your code correctly you just need to use
document.querySelectorAll(.class)
and then loop through them withdocument.addEventListener('click', 'your function()')
I agree with @mihail nicoara
I’ve done this snippet just after your edit, so this is perhaps a cross post.