Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!