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

154
Visualizações
Error event listener not working for invalid background-image url in inline style

I have a simple div which is supposed to contain an image. In order to do that, I add the background-image: url(). The background url can only be added via JavaScript and not via a class. In order to manage error, I tried to add an error event listener on the div in order to get notified when the url is not good but it does not work. I would like to avoid to fetch the url manually.

Check the snippet code:

const el = document.getElementById('test');
el.addEventListener('error', () => {
  console.log('ERROR');
});
el.style.setProperty('background-image', 'url(img.png)');
.default {
  height: 84px;
  width: 112px;
  background-color: green;
  border-radius: 3px;
  cursor: pointer;
}
<div id="test" class="default"></div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use hidden image to capture the error:

<img id="image">
const img = document.getElementById('image');

img.addEventListener('load', event => {
  el.style.setProperty('background-image', `url(${event.target.src})`);
});

img.addEventListener('error', () => {
  console.log('ERROR');
});

img.src = 'img.png';
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