Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image size with Jquery

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.

like image 494
Ryan Avatar asked Mar 09 '11 01:03

Ryan


2 Answers

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').

like image 128
Chris W. Avatar answered Nov 10 '22 00:11

Chris W.


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:

  • height()
  • width()
like image 45
David Thomas Avatar answered Nov 10 '22 01:11

David Thomas