2

I am using the Masonry Plugin and for it to work correctly with images, you need to set the width and height within the image tag. All the image's heights will vary, but the width will be set at 200px.

Is there a way for Jquery to detect the height of each image and set it's height? That way I don't have to go set the height of every single image.

Does this make sense?

Hope someone can help! I am new to Jquery.

Ryan
  • 2,144
  • 8
  • 28
  • 39

1 Answers1

2

Yes there is, you can use jquery custom selectors like this:

//Add custom selector that returns all objects taller than 200px
//See http://www.bennadel.com/blog/1457-How-To-Build-A-Custom-jQuery-Selector.htm
$.extend($.expr[':'], {
    over200pixels: function(a) {
        return $(a).height() > 200;
    }
});

//  Seclect all images taller than 200px
//  Set height to 200px using .css() method 
//  See http://api.jquery.com/css/ 
$('img:over200pixels').css("height","200px");

Credit where credit is due: jQuery Tips and Tricks

Online demo: http://jsfiddle.net/hvq5m/

Community
  • 1
  • 1
amosrivera
  • 26,114
  • 9
  • 67
  • 76
  • Does that code do something like this? http://php.net/manual/en/function.getimagesize.php I am so new at jquery... ha. – Ryan Mar 08 '11 at 23:59
  • Added a more details description to my answer. The code selects images taller than 200px and sets their height to 200px. – amosrivera Mar 09 '11 at 00:08
  • If the image is 200px wide by 300px in height, i need the script to see that it's 300px in height and set it to it so the other image can load correctly below it. http://desandro.com/demo/masonry/docs/#images – Ryan Mar 09 '11 at 00:14
  • have you tried the solution i posted? it seems masonry itself can handle media like this: `$(window).load(function(){ $('#wrapper').masonry({ columnWidth: 200 }); });` have you tried that ? note that image resizing can also be done with php if you feel more comfortable with that language – amosrivera Mar 09 '11 at 00:19
  • Take a look at this... http://jsfiddle.net/ryanjay/fgNMJ/ It works fine within jsFiddle, but not correctly locally or on the server. Perhaps you can place your code where it needs to be... Like i said, Jquery is all new to me ha. I am trying to stay away from PHP. – Ryan Mar 09 '11 at 00:27
  • I'm sorry, i'm not really sure what you want to achieve. – amosrivera Mar 09 '11 at 00:41
  • http://www.ryanjay.com/layouttest the problem is, for masonry to work, it needs a set width/height of each image. I don't know how to implement your code within the http://www.ryanjay.com/layouttest/jquery.custom.js file. Some image's heights will be the same, some will differ, but they can't be set at a single height of just 200px... Does this make sense? – Ryan Mar 09 '11 at 00:53