External images that could not load should alter div

Hello,

I have a few <div> with <img> and the img source is external images.
Sometimes the source does not exist and in that case i would like to alter the <div> or maybe hide it.

the different ways to do this that i can think of is either check if file exits via php/curl but this would be quite heavy loading, so maybe i could do it via javascript.

But it would also not be nice to the client with a lot of extra lookups, is there any way to only check if image was sucessfully loaded at the client or not or could this be done in another way?

This answer as received 50 likes on Stackoverflow at https://stackoverflow.com/questions/9022427/see-if-src-of-img-exists

You can use the error event:

var im = document.getElementById('imageID'); // or select based on classes
im.onerror = function(){
  // image not found or change src like this as default image:

   im.src = 'new path'; // perhaps a path to a 2px blank png
};

Inline Version:

<img src="whatever" onError="this.src = 'new default path'" />

Or

<img src="whatever" onError="doSomething();" />

tag supports these events:

    abort (onAbort)
    error (onError)
    load (onLoad)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.