I have a function I'm using to make any elements on a page with the class equalheight
all the same height (the height of the tallest element):
equalheight = function(container){
var currentTallest = 0,
currentRowStart = 0,
rowDivs = new Array(),
$el,
topPosition = 0;
$(container).each(function() {
$el = $(this);
$($el).height('auto')
topPostion = $el.position().top;
if (currentRowStart != topPostion) {
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
rowDivs.length = 0; // empty the array
currentRowStart = topPostion;
currentTallest = $el.height();
rowDivs.push($el);
} else {
rowDivs.push($el);
currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
}
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
});
}
$(window).load(function() {
equalheight('.equalheight');
});
$(window).resize(function(){
equalheight('.equalheight');
});
The problem I'm running in to is that, let's say I have two rows of boxes. The first row I want all to be the same height, so I give them the class equalheight
. Okay. Good. Now, I also want the second row of boxes to be all the same height, but just of those boxes in the second row.
Is there any way I can modify this code to allow me to set equal height of multiple groups of elements? For example, maybe something like setting the class as equalheight1
, equalheight2
, etc.?
EDIT: One thing I thought about was adding a data attribute on to each element and just calculate the tallest element for each element with the same data attribute..? Like:
<div class="equalheight" data-equalgroup="1"> </div>
We iterate through all elements and add them to the currentRow
columns, and updating the maximum height. When we reach an element that its top differs from previous one, we update all heights of currentRow
columns and then we set currentRow
to a new one, finally after exiting from the loop, we update the last row columns' height.
equalheight = function (container) {
var currentRow = { cols: [], h: 0 };
var topPostion = -1;
$(container).each(function () {
var $el = $(this);
$($el).height('auto')
if (topPostion != $el.position().top) {
for (var j = 0; j < currentRow.cols.length; j++) {
currentRow.cols[j].height(currentRow.h);
}
topPostion = $el.position().top;
currentRow = { cols: [], h: 0 };
}
currentRow.cols.push($el);
if ($el.height() > currentRow.h) {
currentRow.h = $el.height();
}
});
for (var j = 0; j < currentRow.cols.length; j++) {
currentRow.cols[j].height(currentRow.h);
}
}
$(window).load(function() {
equalheight('.equalheight');
});
$(window).resize(function(){
equalheight('.equalheight');
});
here is a fiddle for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With