An XHTML Valid Onerror Handler
<< October | November | December >>
Thursday, 19th November 2009
You might have come across this simple technique that is often used to replace an image that didn't load with a default image (for example an "image not available" picture).
<img src="oidfj.gif" alt="Test" onerror="this.src='test.gif';" id="testimg" />
The problem is, this doesn't validate as valid markup if you're using XHTML as onerror (even in lower case) isn't a valid attribute. However, if you put it into a script block it does still work - and it's even valid...
<img src="oidfj.gif" alt="Test" id="testimg" />
<script type="text/javascript">
<!--CDATA
document.getElementById("testimg").onerror = function () { this.src='test.gif'; };
-->
</script>
I haven't attempted this in a separate script file, for example - adding the handler to many images in an include file or using jQuery - you might find that if you leave it too late your onerror event fires before you've added the handler - so you'll need to put this close to the image in the lifecycle of the page.