homepage Welcome to WebmasterWorld Guest from 54.205.242.179
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Subscribe to WebmasterWorld
Visit PubCon.com
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
rescueme




msg:4408708
 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?

Thanks,

- Jeff

 

Fotiman




msg:4408717
 9:31 pm on Jan 19, 2012 (gmt 0)

What you need is a closure.
For example:
[webmasterworld.com...]

Or

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

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.
Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About
© Webmaster World 1996-2014 all rights reserved