Skip to Navigation or
Skip to Content

An XHTML Valid Onerror Handler

Feeds

RSS Feed

<< 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.

 

You Are Here: Home » Blog » An XHTML Valid Onerror Handler

 

I use a cookie on this website. This cookie doesn't contain or relate to any personal information and it isn't shared with any other website, it just ensures that I don't count you more than once in my website statistics. The Privacy and Electronic Communications Regulations require me to ask your permission to use this cookie, so please indicate below that you are happy for me to do this - I will remember your selection with a cookie, so if you accept I won't ask again...