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:
Use the error handler like this: $('#image_id'). error(function() { alert('Image does not exist !! '); });
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:
error
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With