6

I have a list of images

<img src="001.jpg"> 
<img src="002.jpg">
<img src="003.jpg">
<img src="004.jpg">
<img src="005.jpg">

Each image is 200px wide but the heights are different. Is there a way with Jquery to find, and then set the height of each image after they load?

I plan on having dozens of images on a single page and don't want to add the width and height attribute to every single image tag.

I am using the Masonry Plugin and it requires a width and height attribute for images.

Ryan
  • 2,144
  • 8
  • 28
  • 39

4 Answers4

7

I believe this will do what you want:

$('img').each(function() {
    $(this).attr('height',$(this).height());
    $(this).attr('width',$(this).width());
});

You will probably also want to add a class="masonry" attribute to each img as well and then make your selector $('img.masonry').

Chris W.
  • 37,583
  • 36
  • 99
  • 136
4

You could try:

$('img').each(
    function(){
        var height = $(this).height();
        var width = $(this).width();

        $(this).attr({'height': height, 'width': width});
    })

Assuming that you want the height/width attributes to be set to the img's actual height/width, rather than scaled/modified in some manner.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • I think I am scaling the images. Take a look at the project here: http://jsfiddle.net/ryanjay/fgNMJ/ Now it works within jsFiddle, but on a server it doesn't... http://www.ryanjay.com/layouttest Where would I add this code to find the heights of each image and set them? – Ryan Mar 09 '11 at 02:38
1

You could use the jQuery .height() and .width() methods, as these return the computed width and height. You should always include the width and height attributes in your img tags however, as some browsers will not render these images correctly without them.

Chris
  • 4,762
  • 3
  • 44
  • 79
0

Sure, use the height method to get the size of the img tags.

http://api.jquery.com/height/

andypaxo
  • 6,171
  • 3
  • 38
  • 53