Sunday, September 20, 2009

Avoiding the dreaded red X

Just a simple little thing, but I only thought of it recently. Sometimes, for various reasons, a dynamically loaded image occasionally fails. I used to live with the little red 'x' that would occur in these cases, but eventually realised that there's a more elegant solution -- use the onerror handler to replace that with a tasteful default image. Here's how I do it.



<html>
<head>
<script type="text/javascript">
function pagePreviewError() {
try {
var elem = document.getElementById('page_preview');
elem.src = "res/img/rhs_preview/default.png";
}
catch (e) { }
}
</script>
</head>

<body>
<div id="pagePreview" class="img-shadow">
<img class="content" id="page_preview" onerror="pagePreviewError()" src="res/img/rhs_preview/null.png" /> <!-- generate an error, get the default image -->
</div>
</body>
</html>