Skip to content Skip to sidebar Skip to footer

See If Src Of Img Exists

when I place an img tag I create the src attribute dynamically. Is there a way of testing if the src (path where the image is located) actually exists with javascript in order to a

Solution 1:

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';
};

Inline Version:

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

Or

<imgsrc="whatever"onError="doSomething();" />

<img> tag supports these events:

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

More Information:

Solution 2:

you can make a previous ajax call (with head method) and see the server return code or you can use onerror event to change url or make it hidden, e.g.

<imgsrc="notexist.jpg"onerror="this.style.visibility = 'hidden'">

(I've used inline attribute just to explain the idea)

Solution 3:

If you create the src dynamically with javascript you can use this:

var obj = newImage();
    obj.src = "http://www.javatpoint.com/images/javascript/javascript_logo.png";

if (obj.complete) {
    alert('worked');
} else {
    alert('doesnt work');
}

Solution 4:

You're approaching this the wrong way. When you generate your links with the server side script, check it there whether the file exists or not (by using file_exists() in PHP for example).

You shouldn't rely on JavaScript when you can do it in the server side, as JavaScript can be altered and disabled.

Ask yourself how are you generating the src= attributes, and check there whether the file exists or not, and provide an alternative.

Post a Comment for "See If Src Of Img Exists"