Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
My Image Modal isn't working after changing from ID to Class

I have an image modal and I had it on the image from ID which obviously didn't work, so I changed id to class and now the image modal isn't working at all and I can't see what's wrong with it. All and any help is appreciated.

HTML Modal

            <div id="myModal" class="modal">

                <span class="close">x</span>

                <img class="modal-content" id="img01">

                <div id="caption"></div>
            </div>

Image PHP

"<tr><td><img class='myImg' src='" . $fileName . "' alt=' ". $obj->Description . "' width='50px'>" .

Javascript

var modal = document.getElementById("myModal");

var img = document.getElementsByClassName("myImg");
for(var i=0; i<img.length; i++){
    var modalImg = document.getElementById("img01");
    var captionText = document.getElementById("caption");
    img[i].addEventListener = ('click', function(){
        modal.style.display = "block";
        modalImg.src = this.src;
        captionText.innerHTML = this.alt;
    })
}
var span = document.getElementsByClassName("close")[0];

document.addEventListener("keydown", function(event) {
    const key = event.key;
    if (key === "Escape") {
        modal.style.display = "none";
    }
})

span.onclick = function() {
    modal.style.display = "none";
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The click event listener in the for loop is wrong. You are currently assigning the callback function to the addEventListener method.

img[i].addEventListener = ('click', function(){

This should be:

img[i].addEventListener('click', function() {
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!