Im trying to catch when an image fails loading with a specific reason, say, Denied load of "url"
. I tried using onerror
but that fires with every error. Is there a way to specify the onerror
or any other way to do it?
Asked
Active
Viewed 3,584 times
0

Matias Rozenblum
- 3
- 1
- 4
2 Answers
1
you can do it in this way
<img src="image.png" onerror="imgError(this);"/>
now you can call a function on this like,
function imgError(image) {
image.onerror = "";
image.src = "/images/noimage.gif";
return true;}

Muhammad Shaharyar
- 1,044
- 1
- 8
- 23
-
Sorry but, that works for all errors too, how can I discriminate between them? My image throws 2 errors, "Denied load of" and "ERR_FAILED", I need the webpage to do different things for each error. – Matias Rozenblum Jan 31 '17 at 13:51
-
what are you getting in (image) parameter ? – Muhammad Shaharyar Jan 31 '17 at 13:55
-
i'm getting all the document, i'm guessing because i create the image in a javascript. – Matias Rozenblum Jan 31 '17 at 14:11
0
It´s not posible, but usually the problem is something like this : " Error 404 resource found " or "Failed to load resource: net::ERR_FILE_NOT_FOUND ".
But you can make ajax request with type GET and catch the error.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function CheckImageError(img){
var urlimg = img.attributes.src.ownerElement.currentSrc ;
$.ajax({
type:"GET",
url:urlimg ,
context: img,
error:function(requestObject, error, errorThrown){
// trace console.log or other action
},
complete: function(){
//do something
$(this).css("border","1px solid red");
}
})
}
</script>
<img onerror="CheckImageError(this)" src="image.gif">
You can check xmlhttpRequest Object properties

Angel Fraga Parodi
- 750
- 10
- 20
-
Okay, i'm trying your solution. Why does currentSrc gives me ""? img.attributes.src.ownerElement gives me the img object with it's src, but currentSrc turns it to "". – Matias Rozenblum Jan 31 '17 at 14:08
-
-
Somehow it still executed complete callback. I tried to erase ownerElement.currentSrc and then it executed error but errorThrown was empty, any ideas? – Matias Rozenblum Jan 31 '17 at 14:22
-
Okay, i didnt see the screenshot before, my requestObject has status: 0 and statusText: "error". That's not good right? – Matias Rozenblum Jan 31 '17 at 14:44
-
If you are testing on local file without server can be the reason. or maybe http://stackoverflow.com/questions/2000609/jquery-ajax-status-code-0 – Angel Fraga Parodi Jan 31 '17 at 15:36
-