Jquery - set height for every 2 or 3 elements

I have several divs per page in columns of 2, so every 2 divs should have the same height. As far as I can tell that the plugins available for forced equal height make all elements the same height, I just need each pair to be the same height.

my markup is as follows

etc.

I have the following jquery that works, but I'm sure it can be made easier

{ var rowOneHeight = Math.max($('div.large:eq(0)').height(),$('div.large:eq(1)').height()); $('div.large:eq(0)').css('min-height', rowOneHeight); $('div.large:eq(1)').css('min-height', rowOneHeight); var rowTwoHeight = Math.max($('div.large:eq(2)').height(),$('div.large:eq(3)').height()); $('div.large:eq(2)').css('min-height', rowTwoHeight); $('div.large:eq(3)').css('min-height', rowTwoHeight); var rowThreeHeight = Math.max($('div.large:eq(4)').height(),$('div.large:eq(5)').height()); $('div.large:eq(4)').css('min-height', rowThreeHeight); $('div.large:eq(5)').css('min-height', rowThreeHeight); 

}

he would also need to do the same with a group of three divs. Thanks

+4
source share
1 answer

You can loop with .slice() to scroll in sets 2, for example:

 var elems = $("div.large"); for(var i = 0; i < elems.length; i+=2) { var divs = elems.slice(i, i+2), height = Math.max(divs.eq(0).height(), divs.eq(1).height()); divs.css('min-height', height); } 

Or, for a more general approach, since you want to do this with 3, and here is the plugin form:

 $.fn.setMinHeight = function(setCount) { for(var i = 0; i < this.length; i+=setCount) { var curSet = this.slice(i, i+setCount), height = 0; curSet.each(function() { height = Math.max(height, $(this).height()); }) .css('min-height', height); } return this; }; 

Then you can call it like this:

 $("div.large").setMinHeight(2); //or 3, etc 

Here you can check it out .

+7
source

All Articles