see if src of img exists
53,041
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:
<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:
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.
<img src="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 = new Image();
obj.src = "http://www.javatpoint.com/images/javascript/javascript_logo.png";
if (obj.complete) {
alert('worked');
} else {
alert('doesnt work');
}
Author by
Tono Nam
Updated on September 02, 2022Comments
-
Tono Nam almost 2 years
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:
-
Hector Sanchez over 12 yearsI saw in other forums, that it doesn't work in IE, is that correct?
-
Hector Sanchez over 12 yearsRight, thanks! Probably earlier versions, who knows xD thanks.
-
sasjaq almost 11 yearsand what happens, when new_default_path doesn't exists? will it be an infinity loop?
-
Yigitalp Ertem over 8 yearsThe image exists in the following path, but it says 'no worky' when I run code snippet. Is it because of 'same origin policy'?
-
tropicalfish over 8 yearsI prefer doing it in other way so that the UI won't wait until
onError
to hide the image, causing the broken img icon to flash.<img src="somephoto.png" style="visibility:hidden;" onload="this.style.visibility='visible'" />
-
tj-recess over 7 yearsAwesome example. Works like a charm.
-
Mohamed Allal over 6 yearsit is because, obj.complete return false. the code get executed right away. while the state isn't in complete yet. so it always go to else block
-
nimai over 5 yearsThis is very subjective: "You shouldn't rely on JavaScript when you can do it in the server side". I fully disagree, and the rationale is simply wrong. It's not because code can be altered that the user has an interest in doing so. The OP probably just wants to adapt the style of a web app if the image doesn't exist. Style is something that is in the client domain, and IMO, it should never occur server-side. Your point would be valid if the image was a secured resource that needed authentication to be displayed for example.