views:

134

answers:

2

At first image height is coming as zero, after that by refreshing the page i am getting its actual height. I need to get its height at first time? could any body helps me?

$j(document).ready(function(){
           var imgV = new Image();
           imgV.src="http://www.kerrvilletexascvb.com/Riverside%20Nature%20Center3.JPG";
           $j("#imgD").html(imgV.height);
           alert(imgV.height);
});


<div id="imgD"></div>
<img src="http://www.kerrvilletexascvb.com/Riverside%20Nature%20Center3.JPG" />
+1  A: 

The image size is only available when the image is loaded. Likely when you reload the page, the image is instantly served from cache, so its size is instantly available.

If for whatever reason you need to get the size before you display an image, you can display it off-screen to begin with. Add an onload handler to it that will get called when the image is ready - you can then inspect it's size, and attach it where needed.

By displaying off-screen, I mean stick it into a 1x1 pixel div with overflow: hidden style, somewhere on the bottom of the page.

levik
Or better yet, position absolute way off to -9999px left/top or something; then you don't have to worry about the content being large enough to possibly get to your hidden div.
Daniel Lew
Why do you need to display the image off-screen at all? Can't you just attach an 'onload' handler to the image and then [in the handler] get the image dimensions via 'image.width' and 'image.height'?
Steve Harrison
+6  A: 

You don't have to insert an image into the DOM to get its dimensions:

$("<img />")
    .attr("src", "http://www.google.com/intl/en_ALL/images/logo.gif")
    .load(function() {
        alert(this.width);
        alert(this.height);
    })
;
nickf