views:

110

answers:

3

How to retrieve the Image height and width from the IMG tag using jQuery and use this value in div style.

like

<div class=top>&nbsp;</div>
<img src="source.jpg" width="200" height="400" alt="" />
<div class="bottom">&nbsp</div>

I want to use the height of the Image and and apply to the DIV. like 400px-20px. div width.

THanks

+8  A: 

You can use the attributes

$("img[src=source.jpg]").attr("width");
$("img[src=source.jpg]").attr("height");

Or you can use the dimension methods (they are calculated by jQuery):

 $("img[src=source.jpg]").width();
 $("img[src=source.jpg]").height();

Edit (Modifying your divs)

$("div.top").add("div.bottom").css({ 
      width: $("img[src=source.jpg]").attr("width") - 20,//<- your minus 20 goes here
      height: $("img[src=source.jpg]").attr("height")
});
Ghommey
just to note, if you want to get the width and height without the border and padding widths, use innerWidth() and innerHeight().
Rowan
I want to subtract the 20px from the Retrieved image width. how to do that??
Wazdesign
var width = $("img[src=source.jpg]").attr("width")-20;
Rowan
+1  A: 

You have 2 ways to get height/width of an image.

1) var height = $("img").attr("height");

See http://docs.jquery.com/Attributes/attr

2) var height = $("img").height();

GOOGLE IT!

Zayatzz
+2  A: 

You should add a class name to your image tag to make it more easily accessible using jQuery:

<img src="source.jpg" class="yourClassHere" width="200" height="400" alt="" />

You will then be able to directly access that particular image's height and width and not any other images on the page. This is the full example, performing the actions after the document is ready.

$(function() {
    var $img = $('img.yourClassHere');
    $('.top, .bottom').css({ height: $img.attr('height'), width: $img.attr('width') }); 
});

I have also added some speed improvements to the script by reducing the DOM traversals to access your image.

cballou
If all the images are in one section you could add a class name to the wrapper `div` instead.
DisgruntledGoat