OK, I’ve got the onError javascript working nicely. However, in most cases I need to try an alternate image and if THAT is broken as well, it needs to fall back to a local default image.
On the initial broken image (http://somesite.com/someimage.jpg), this code correctly loads the alternate image that is passed. However, as you can see from the code, I’m trying to reset the source.onerror so that if the alternate image is broken as well, it will just load the local default image (/some/local/file.jpg). However, defaultImage() is never called. It’s not a matter of passing in the “this” either because if I change it to source.onerror="alert('hi')"; it never gets called anyway.
It appears that when the page loads, it only kicks of onerror once and never tries it again. Is there some way I can force the DOM to try loading the img again so that the new onerror function will kick off if the alternate image is broken?
<img src="http://somesite.com/someimage.jpg" onerror="AltImage(this, 'http://sommesite.com/otherimage.jpg');"/>
<img src="http://somesite.com/someimage.jpg" onerror="AltImage(this, '');"/>
<script>
function AltImage(source, alt_image){
if (alt_image !=""){
source.src = alt_image;
source.onerror = "defaultImage(this)";
return true;
}
source.src = "/some/local/file.jpg";
source.onerror = "";
return true;
}
function defaultImage(source) {
source.src = "/some/local/file.jpg";
data.onerror="";
return true;
}
</script>
You can check if the image exists or not by using the function below instead of your method :