Tono Nam
Tono Nam

Reputation: 36070

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 avoid getting:

enter image description here

Upvotes: 30

Views: 58476

Answers (5)

Devmyselz
Devmyselz

Reputation: 460

easy

var x = new XMLHttpRequest(); x.open("get", "your_url.com/image.ext or /image.png or image.jpg", true);x.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) {alert('exist');}else{alert('does not exist'};}; x.send();

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382909

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:

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

Or

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

<img> tag supports these events:

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

More Information:

Upvotes: 67

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

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

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

Upvotes: 6

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175098

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.

Upvotes: -1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123438

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.

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

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

Upvotes: 16

Related Questions