Damaged images, how to modify the JavaScript

76 views Asked by At

I have this code that displays a different image in place of a broken image link. The problem is that the script changes not only "damaged" images, but also images that display without a problem. How can I modify the code below?

 $("img").each(function () {
          if (
            (typeof this.naturalHeight != "undefined" &&
              this.naturalHeight == 0 &&
              this.naturalWidth == 0) ||
            this.readyState == "uninitialized"
          ) {
            $(this).attr(
              "src",
              "http://some-photo.blabla.png"
            );
          }
        });

I'm taking my first steps in programming.

Modifying the code so that it only fixes broken links, not all of them.

2

There are 2 answers

1
Ivan On

Your code should be executed after the page is fully loaded

$(document).ready(function () {
   $("img").each(function () {
      if (
        (typeof this.naturalHeight != "undefined" &&
          this.naturalHeight == 0 &&
          this.naturalWidth == 0) ||
        this.readyState == "uninitialized"
      ) {
        $(this).attr(
          "src",
          "http://some-photo.blabla.png"
        );
      }
    });
 }
0
Rafal On

I found a solution, of course with your help. Thank you!

 var delayscript = function(){
$(document).ready(function () {
   $("img").each(function () {
      if (
        (typeof this.naturalHeight != "undefined" &&
          this.naturalHeight == 0 &&
          this.naturalWidth == 0) ||
        this.readyState == "uninitialized"
      ) {
        $(this).attr(
          "src",
          "http://some-photo.blabla.png"
        );
      }
    });
 })
  };
setTimeout(delayscript, 10000);