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