Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

348
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda