Wasim Shaikh
Wasim Shaikh

Reputation: 7030

How can I retrieve the attributes of images?

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

Upvotes: 0

Views: 275

Answers (3)

jantimon
jantimon

Reputation: 38160

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")
});

Upvotes: 8

Corey Ballou
Corey Ballou

Reputation: 43547

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.

Upvotes: 3

Odif Yltsaeb
Odif Yltsaeb

Reputation: 5676

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!

Upvotes: 1

Related Questions