homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

How do I change image.onload function content?
image.onload function

5+ Year Member

Msg#: 4408706 posted 8:53 pm on Jan 19, 2012 (gmt 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



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

Msg#: 4408706 posted 9:31 pm on Jan 19, 2012 (gmt 0)

What you need is a closure.
For example:


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

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved