JavaScript Array Max and Equal Height Columns
February 12th, 2009
JavaScript has a Math.max function that allows you get the maximum between two numbers. That is cool, and all, but I rarely want to compare two numbers. More often, I’m looking for the maximum number of an array. For example, on a recent project, I wanted all children of an elements to be the same height. I didn’t want to deal with Faux columns and I was ok with relying on JavaScript this time.
The best way to set columns to an equal height is to just grab all the heights, get the max, and then set each element height to the max. I did a bit of search around and found an example of adding max to Array’s prototype. I wrapped that in an if statement that checks if max is currently defined, that way if max gets added to Array in the future, my version won’t conflict.
if (typeof Array.prototype['max'] == 'undefined') {
Array.prototype.max = function() {
return Math.max.apply({},this);
}
}
The trick in the code above is that using apply on the built in function allows max to receive an unlimited number of arguments. This allows me to do the following:
[1,2,3].max() // => 3
In this instance (making equal height columns), I ended up with the following solution.
$.fn.equalHeightChildren = function() {
return this.each(function() {
var children = $(this).children();
var tallest = $.map(children, function(child) {
return $(child).height();
}).max();
children.each(function() {
var padding = parseInt($(this).css('padding-top')) +
parseInt($(this).css('padding-bottom'));
$(this).height(tallest - padding);
});
});
}
I use $.map to loop through the children and return an array of their heights. At the end of map, I call max() to return the greatest height. The nice thing about this solution is that it even takes into account padding and the box model.