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.

Logging for the Lazy

February 11th, 2009

Creating a Network Bar with jQuery

January 23rd, 2009

New Blog about Blogging

January 12th, 2009

Refactoring Tip: Move Functions into Objects

December 16th, 2008

Refactoring Tip: Introduce Explaning Variables

November 24th, 2008

Creating A jQuery Plugin From Scratch

November 20th, 2008

An Idea Idea

November 11th, 2008

4 Weight Lifting Tips

November 1st, 2008

Do It For Mom

October 31st, 2008

About This Site

Addicted to New is the personal website of John Nunemaker (Noo-neh-maker), a Web Developer enamored of Ruby on Rails and a wide-eyed fan of all things new and cool.