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

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

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 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