Forum Moderators: open
<html>
<head>
<title>image preloader, with load failure default & onclick demo</title>
<script>
[red]//........ params............[/red]
var imageDir = "images/"var roll_images =
{
not_found:"image_not_found.jpg",
[red]// above: default image path. must be first[/red]
apple : "orchard.jpg",
orange : "bears_like_marmalade.jpg",
banana : "idontexist.jpg" [red]// no comma[/red]
}
[red]//............................[/red]preload(roll_images,imageDir)
[red]//........functions...........[/red]
function preload(images, path)
{
[red]// swap src strings for images objects
// assign onerror event method[/red]
var tempSrc;
var image;
for(var key in images)
{
tempSrc = images[key]
image = images[key] = new Image()
image.onerror = regError
image.key = key
image.src = path + tempSrc
}[red]// 'inner function'[/red]
[red]// if error, swap for default image[/red]
function regError()
{
if(this!= images['not_found']) [red]// no default for default![/red]
images[this.key] = images['not_found']
else
images['not_found'] = null
}
}function roll(key, targetId)
{
var image = roll_images[key]
if(!image) return false [red]// check for bad default[/red]
var target = document.images[targetId]
target.src = image.src
}</script>
</head>
<body><a href="javascript:roll('apple', 'display');void 0">Link 0</a>
<a href="javascript:roll('orange','display');void 0">Link 1</a>
<a href="javascript:roll('banana','display');void 0">Link 2</a>
<br /><br />
<img src="images/spacer.gif" id="display" width="200px" height="425px" /></body>
</html>
Apparently I'm getting different results than you, Bernard, because the first code you posted works fine for me on Mozilla 1.5. The onerror just causes the default image to load. Even did in NS 4.79, though it mangled the width, for some reason.
I'd be careful, lonex00, not all browsers support onload for images. It is only standardized for the body and, to a degree, for frames, for which it depends on the (X)HTML version (usually found in the transitional, not strict spec).
I should add that Opera 7.23 works with both the onerror and background techniques, Moz 1.5 only with the onerror, and IE 6 works with both, but has the red x over the default image with just the background.