1

I am trying to add an image to the end of the page, grab it's height, and width, and use these values to calculate what the height/width of another image on the page will be (This is for an online equation editor I'm building).

I am setting the height with CSS, and would like the width to scale automatically for me. Do I need to do this in jquery, or will the browser do this automatically for me?

Here is an example of the type of thing I'm trying to do.

$( 'body' ).append( '<img class="letter" src="my_image.png">' );
var new_element_height = $('.letter').last().outerHeight();
var new_element_width = $('.letter').last().outerWidth();
$('.letter').last().remove();
alert( new_element_height );
alert( new_element_width );

My CSS is something like:

.letter {
    height: 50px;
}

The new_element_height gives me 50px, new_element_width gives me 0px. I'm guessing this is because I'm dynamically loading these images and then trying to grab the height/width.

I would like the height to be 50px, and the width to scale correctly to that height, and then place those values in the new_element_height/new_element_width variables.

Camden Reslink
  • 323
  • 4
  • 12

1 Answers1

3

It looks like you are trying to get the image dimensions before the image is loaded. See JavaScript: Know when an image is fully loaded

For a working demo check out http://jsfiddle.net/eBrnu/2/ Try setting the height to different values and you will see that the width changes too.

Also, you probably will want to at least set visibility: hidden in your CSS so the image doesn't flicker in and out but still takes up space.

Community
  • 1
  • 1
Nal
  • 2,741
  • 20
  • 14
  • The solution I came up with was to have all of the images on the page in the html with the css set to visibility: hidden. I then accessed the specific heights, and widths I needed by using a unique id for each image. It's unfortunate that I have to load all of these images (there will probably be between 100 and 150 images, and any given user may only use between 10 and 20 of them, but there is no way to tell which ones). I think I'll be able to speed up the load time by using CSS sprites. – Camden Reslink Aug 20 '12 at 04:15