11

I realize for the most part CSS is the best way to achieve even height elements. However, in certain situations where we are dealing with a page or CMS we don't have full control over, I think a jQuery solution would be very handy.

I'm wondering how I would achieve the following in jQuery. I'm not very familiar with jQuery syntax, but here is my watered down pseudo jQuery / English syntax... Does this make sense, or is there a simpler way of achieving this? I realize the following code does not work in the slightest, it's just my way of trying to contribute towards a solution, and pitch in a bit in the logic department:

$('div.columns')each.get.height;
create an array of the height values
grab the largest value in this array
$('div.columns')each.css(height: $max-height);

Once you stop laughing at my pseudo-code, any ideas? Thanks!!

LearnWebCode
  • 1,361
  • 3
  • 12
  • 22

1 Answers1

24

Try something like this:

var maxHeight = -1;
$('div.columns').each(function() {
    if ($(this).height() > maxHeight) {
        maxHeight = $(this).height();
    }
});
$('div.columns').height(maxHeight);

Note: This is an untested code. But it should have the rudimentary concept in place for you. Your original concept was close, but an array is not needed here if you only want to retain the maximum height value.

Bill
  • 3,478
  • 23
  • 42
Cat
  • 66,919
  • 24
  • 133
  • 141
  • 1
    @Eric I know its a bit late but I really want to thank you for this approach. I have been using arrays to do that. I have only question, what does maxHeight = -1 do? If I remove "-1", the code doesn't work. So can you guide me with that? Thank you. – Awais Umar Feb 28 '15 at 07:15
  • 2
    @Symbolwdd Glad it helped! The -1 gives it an initial integer value for comparison. Without that, it would use `undefined`, which can't properly be compared to an integer. – Cat Feb 28 '15 at 16:36
  • @Eric; Thanks for getting back. I got now how the code is working. Really nice approach. Never thought it doing without arrays. Thank you. :-) – Awais Umar Mar 01 '15 at 05:25
  • It should be noted that this code **doesn't include braces in the if statement** (which is [fine](http://stackoverflow.com/questions/4797286/are-curly-braces-necessary-in-one-line-statements-in-javascript)) but if you expand this statement (which I was doing) it won't work and you will need to add them. Had me stumped for a bit until I noticed. – Luke Nov 24 '15 at 20:00
  • 1
    @Luke Thanks for the comment. While braces are fine to be omitted in practice, they shouldn't be in sample code. I've amended my answer. – Cat Nov 24 '15 at 22:21