views:

41

answers:

3

Hello, I have a site where I have to dynamically load images. I must know their width/height before laying them down, so I am using the onload event handler. What I found anyway, is that sometimes those values are 0/0 even in the handler (this happens on Chrome and as I am targeting webkit, this is the browser to use). Is there any way to enforce this? I mean I could use some things like a setTimeout in the case the image is 0/0 and recheck until its done, what I'm looking for is something more clean and possibly using DOM methods...

A: 

is the onload event in the head of your page? I had before some problems when it stands it in the head.

You can also put your javascript before the end of the body. In that case you don't need the onload event.

Tom
man, it is to LOAD IMAGES
gotch4
i know, but without code i can't do much
Tom
A: 

You're using the onload event of the image right? If that's not reliable, I'd try writing the image into the DOM in a hidden element and then getting it's dimensions.

edeverett
Hmmm, so you say that if the image is already in the DOM it'll get dimensioned for sure? Right now I'm using off DOM images created with document.createElement.
gotch4
Yeah, I've not tested it, so not 100% but that's what I'd try. Append the image to a hidden div and then see if it gives you the right dimensions. It makes sense because if the you suddenly made the div visible the browser would have to know the dimensions of the image to render it.
edeverett
A: 

I'm not entirely sure about what you want to achieve. The only reason I can imagine why you would need the image width and height is if you don't want to scale the image. This seems kinda unlikely because it would not make for a clean layout of your page.

If you simply want to preserve aspect ratio, set the images to a certain height and then leave height on auto (e.g. in a CSS class):

 .myImg {
     /* ... */
     width: 150px ;
     height: auto ;
     /* ... */
 }

This way you will have a clean layout preserving the aspect ratio of your images while not having to use scripts to modify their width and height. Images in HTML preserve aspect ratio by default.

HTH

FK82