Click to See Complete Forum and Search --> : Handling the LOAD event of an image


karayan
07-29-2003, 07:05 PM
I need to have a Javascript function handle the LOAD event of an image. The image tag exists in the body, but its src is loaded in Javascript, like so:

document.images[0].src="blabla.jpg";

Now, the problem is that I need to resize this image. If I do it right after the statement above, it may not work, becuase the new image has not been loaded yet. So

document.images[0].width*=ratio;

(to resize by some ratio) does not always work right. So, I figured I need to capture the LOAD event of that image and run a resizing function. First I tried to put the load handler in the <img> tag, but that didn't work. (It only worked for the initial image, but when I redefined the src via Javascript, it never fired the resizing function.)

So, I tried:

this.captureEvents(Event.LOAD);
document.images[0].handleEvent;
document.images[0].onload="resizeImage()";

before changing the src, but IE complains (Event.LOAD undefined --- I have no idea why, since I took this code from my JS book).

So, how do I do this?

Charles
07-29-2003, 08:23 PM
Here's a working example of setting an image's 'onload' handler.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<title>Example</title>

<img alt="[Bettie Page}" src="http://www.bettiepage.com/images/photos/bikini/bikini1_a.jpg">

<script type="text/javascript">
<!--
Array.prototype.next = function () {if (isNaN(this.n) || this.n >= this.length) this.n = 0; return this[this.n++]};

betties = ['http://www.bettiepage.com/images/photos/bikini/bikini1_a.jpg', 'http://www.bettiepage.com/images/photos/bikini/bikini2_a.jpg', 'http://www.bettiepage.com/images/photos/bikini/bikini3_a.jpg', 'http://www.bettiepage.com/images/photos/bikini/bikini4_a.jpg']

document.images[0].onload = function () {this.src = betties.next()}
// -->
</script>