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

98
Views
backup image for dynamically updating image sources

I have a program with dynamically updating images which I'm updating from a script, when it canat find an image, I want it to show a backup image. I've tried using this onerror="this.onerror=null;this.src= piece of code in the html img tag, but it only works once and does not work once the img source is updated from the script. I am not sure how to work around this.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As I commented above it should be server side implementation.

But I wrote a client side code for you.

You just need to add a "imgSrcArr" containing all the possible and alternate sources in a Array. And keep checking the dimension of the img element. If dimension is 0, just change the source.

<body>
    <img src="null0" />
</body>
<script>
    window.addEventListener("load", (event) => {
      var image = document.querySelector("img");

      var imgSrcArr = ["null1", "null2", "https://picsum.photos/200/300"];

      let index = 0; // img index to be incremented

      let thisInterval = setInterval(() => {
        var isLoaded = image.complete && image.naturalHeight !== 0;
        console.log("Checking Image => " + index);
        if (isLoaded) {
          // if image is loaded
          console.log(isLoaded);
          console.log("Image loaded :)");
          clearInterval(thisInterval); // clearInterval
        } else {
          console.log("Changing img source=> " + index);
          image.setAttribute("src", imgSrcArr[index]);
          if (index <= imgSrcArr.length) {
            index++;
          }
        }
      }, 2000);
    });
</script>
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!