Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

346
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda