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

347
Views
Adding Event Listener to an image created in js

I'm trying to create a bunch of images inside js and add Event Listeners to each of them so that they trigger function when clicked.

I use this function to create images.

function image(fileName) {
    const img = new Image(100, 100);
    img.src = `images/${fileName}`;
    return img;
}

When I try to add an event listener with image.addEventListener(...) It compiles but doesn't work when drawing the images later.

I have also tried adding an id to the image and using getElementById() to add the listener, it doesn't compile with the event listener reading null.

Any suggestions?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The eventListeners only work when the element is added to the DOM, which isn't in your case.

If you add your image to the DOM then you can add a working evenListener.

function image(fileName) {
    const img = new Image(100, 100);
    img.src = `images/${fileName}`;
    // Or any other node
    document.body.appendChild(img);
    return img;
}
// Now you can bind eventListeners to the returned img element
about 4 years ago · Juan Pablo Isaza 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!