PDA

View Full Version : Get Image Width from Select List



dotcomtim
10-27-2006, 12:28 AM
I have the following script that I have created to get the image wiidth and pass it to a text field.

My first problem I am having is that the image width works but it doesn't do it all the time. It seems to be selective about it, I am doing it wrong?


<form method="post" action="">
<script type="text/javascript">
function getwidth(imgId,strPath)
{
var img = new Image();
img.src = strPath;
alert(img.width);
}
</script>

<select name="photo1" id="photo1" class="formselect" onchange="getwidth('photo1',this.value);">

<option value="" selected="selected">Choose A Photo</option>
<option value="photo1.jpg">photo1.jpg</option>
<option value="photo2.jpg">photo2.jpg</option>
<option value="photo3.jpg">photo3.jpg</option>
<option value="photo4.jpg">photo4.jpg</option>
<option value="photo5.jpg">photo5.jpg</option>
<option value="photo6.jpg">photo6.jpg</option>
<option value="photo7.jpg">photo7.jpg</option>
<option value="photo8.jpg">photo8.jpg</option>
<option value="photo9.jpg">photo9.jpg</option>
<option value="photo10.jpg">photo10.jpg</option>
</select>

<input size="4" name="photo1_size" id="photo1_size" value="" readonly="yes">
</form>

jscheuer1
10-27-2006, 07:11 AM
Nope, you've got it about right. The problem is that the browser must first load the width property of the new Image() object before it will have access to it for reporting purposes. Different browsers do this at different points in the overall image loading process, IE being the one that takes the dimensions earliest - at least as far as I can tell from playing around with this sort of thing. However, unless the image is very small and the bandwidth very is high, or the image is already cached, no browser will get the width property before the script code that you have there executes. So, in a first time live execution, most of the time, no browser will get the width property.

If you preload all of the images ahead of time, and later query their widths, you should get good results as long as each image maintains its own uniquely named image object and you query the correct one for a particular image. You also may be able to work out a setTimeout() loop to keep checking if the value of img.complete is true and, then once it is, break out of the loop and go for the width value. The most reliable way of dealing with image's dimension values on the web is to just tell the browser using width and height attributes in an image tag. The visibility of the tag may be hidden and it can be positioned off screen if desired. This is useful in certain preloading schemes.