Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

How do I change image.onload function content?

image.onload function

8:53 pm on Jan 19, 2012 (gmt 0)

New User

5+ Year Member

joined:Jan 12, 2009
posts: 24
votes: 0

I have an image "onload" function which needs to be applied to a series of images on a web page. It looks like this now:

mypics[x].onload = function() { imageheight[x]=this.height };

Let's say there are 100 images, they are specified in the array mypics[0]-mypics[99].

As each image loads on the page (specified within the array mypics[]), this function will be called, setting the imageheight array to the height of each image.

Here's the trouble, since there are 100 images loading at various times, the onload function counter variable (x) doesn't reflect the value of "x" when the function was set, instead it returns the value of "x" at the time each onload function runs, meaning it no longer points to the appropriate image. So if x is 0 the first time and 99 the last time, it stays at 99 as each onload function fires, meaning the imageheight[] array only has a value for imageheight[99].

Is there a way I can hard code the initial value of a variable into the onload function. For example, something like:

mypics[x].onload = "function() { imageheight["+x+"]=this.height };"

I tried this, and it doesn't work, apparently the function can't be defined within quotes like that. Any suggestions?


- Jeff
9:31 pm on Jan 19, 2012 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 5016
votes: 24

What you need is a closure.
For example:


mypics[x].onload = (function (i) {
return function() {
imageheight[i] = mypics[i].height;