...

View Full Version : OnError on Image



ken_shoti
05-12-2007, 02:50 PM
I'm working on this piece of code on checking for the existence of an image, if not it will load another image...

using onerror in an image, we can do that...

<img src=image.gif onerror="if(this.src.indexOf('replace.gif')==-1){this.src='replace.gif'}">

the if(this.src.indexOf('replace.gif')==-1) is intended to prevent unending loops if ever replace.gif still doesnt exist

but is there a way to check if onerror is true or false?

since after loading the replace.gif image in replacement of image.gif....i want still to be sure that replace.gif does exist...because if not...it will load another final and certified existing image... so is there something like this that i can place like...

if(this.onerror==true){this.src='real.gif'}

Arty Effem
05-12-2007, 03:22 PM
the if(this.src.indexOf('replace.gif')==-1) is intended to prevent unending loops if ever replace.gif still doesnt exist
Just have the handler cancel itself the first time it's called:


<img src='image.gif' onerror="this.onerror=null; this.src='replace.gif'">

ken_shoti
05-12-2007, 03:46 PM
hm...didn't thought of that :)) thanks....
hm...but that onerror=null will not solve my main problem which is to check if replace.gif does exist or not...

glenngv
05-12-2007, 07:14 PM
var imgCtr=0;
function loadNew(img){
imgCtr++;
if (imgCtr==1){
img.src='replace.gif';
}
else{ //2nd error
img.onerror=null;
img.src='real.gif';
}
}

<img src="image.gif" onerror="loadNew(this);" />

ken_shoti
05-13-2007, 03:27 AM
Alright...Ayos!
Thanks for the code!

Arty Effem
05-13-2007, 05:16 PM
Alright...Ayos!
Thanks for the code!That code limits you to one instance per document.


<img src='standard.gif' onerror='replaceImage(this, "backup1.gif", "backup2.gif")'>

<script type='text/javascript'>

function replaceImage(ref,img1,img2)
{
ref.onerror=new Function("this.onerror=null;this.src='"+ img2 +"'");
ref.src=img1;
}

</script>

When testing locally, you will probably find that Mozilla and Opera don't fire the onerror event.

ken_shoti
05-14-2007, 02:58 AM
nice...thnaks for the addition



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum