0

Is there a way to detect when a dynamically created img src path returns an error without using the onerror property in the HTML syntax, but using just a JavaScript file?

My HTML:

    <img class="icon" src="/test.png" alt="Logo">

My JS, using JQuery 3.3.1:

$(document).ready(function() {
    $(".icon").onerror = function() {
        $(this).attr('src', '/res/default-icon.jpg');
    }; 
});

Or also tried like this:

$(document).ready(function() {
    $(document).on("error", ".icon", function() {
        $(this).attr('src', '/res/default-icon.jpg');
    });
});

But it doesn't work. Thanks for the help.

Snorlite
  • 327
  • 1
  • 3
  • 12
  • 1
    Possible duplicate of [Check if image exists on server using JavaScript?](https://stackoverflow.com/questions/18837735/check-if-image-exists-on-server-using-javascript) – Muhammad Usman Jan 04 '19 at 11:25
  • 2
    Try `$(".icon").on("error", .....)` or `$(".icon")[0].onerror = .....` – Titus Jan 04 '19 at 11:32
  • You can do it but only where you dynamically add the image. As far as I know, you can't delegate an error event handler so you can't attach it to a container element and then handle errors from images that you add later. Are you adding the images with your code? – Reinstate Monica Cellio Jan 04 '19 at 11:44
  • The img elements are added with a php script. $(".icon").on("error", .....) still doesn't work – Snorlite Jan 04 '19 at 17:43

2 Answers2

0

You can load images like this:

const createImage = (src, defaultImgSrc=null) => {
  const img = new Image();
  img.triedDefault = false;
  // Specify the error callback
  img.onerror = (err) => {
    if ((defaultImgSrc != null) && (!img.triedDefault)) {
      img.src = defaultImgSrc;
      img.triedDefault = true;
    } else {
      console.error(`Failed to load image from "${src}": ${err}`);
    }
  };
  // Load the image
  img.src = src;
  return img;
};

const img = createImage("whatever/path/icon.png", "/res/default-icon.jpg");
comonadd
  • 1,822
  • 1
  • 13
  • 23
-1

on frontend you can set default background for this images:

<img class="icon" src="/test.png" style="background:url('/res/default-icon.jpg')" alt="Logo">

or with js handle error:

[].forEach.call(document.querySelectorAll(".icon"), (el) => {
    el.onerror = () =>
    {
        if (el.getAttribute("src") !== "/res/default-icon.jpg")
        {
            el.src = "/res/default-icon.jpg";
        }
    }
});
    <img class="icon" src="/test.png" alt="Logo">
    <img class="icon" src="/res/default-icon.jpg" alt="Logo">

you can try fix this on backend, for example set default image on nginx:

location ~* \.(gif|jpe?g|png)$ {
    root /var/www/somesite.com;
    try_files $uri $uri/ default-icon.jpg;
}
Vadim Hulevich
  • 1,803
  • 8
  • 17