colindunn
colindunn

Reputation: 3163

jQuery: get image height, assign to image

This sounds simple enough, but so far I have been unable to solve it. I have a large number of images that for various reasons need to have their height explicitly defined. Assuming no two images have the same height, what would be the best way to find the height of each individual image within div.column and then assign the height as a parameter to the corresponding image?

HTML

<div class="column">
    <ul>    
        <li><img alt="Logo" src="images/logos1.jpg /></li>
        <li><img alt="Logo" src="images/logos2.jpg /></li>
        <li><img alt="Logo" src="images/logos3.jpg /></li>
        <li><img alt="Logo" src="images/logos4.jpg /></li>
        <li><img alt="Logo" src="images/logos5.jpg /></li>
        <li><img alt="Logo" src="images/logos6.jpg /></li>
    </ul>
</div>

<div class="column">
    <ul>    
        <li><img alt="Icon" src="images/icon1.jpg /></li>
        <li><img alt="Icon" src="images/icon2.jpg /></li>
        <li><img alt="Icon" src="images/icon3.jpg /></li>
        <li><img alt="Icon" src="images/icon4.jpg /></li>
        <li><img alt="Icon" src="images/icon5.jpg /></li>
        <li><img alt="Icon" src="images/icon6.jpg /></li>
    </ul>
</div>

Upvotes: 0

Views: 99

Answers (1)

marcio
marcio

Reputation: 10512

Maybe the best way to do it:

$('div.column img').each(function(){
    var image = $(this);
    var realHeight = image.attr("naturalHeight");
    image.attr('height', realHeight);
});

The trick is to access the naturalHeight property instead of access CSS rules.

Upvotes: 1

Related Questions