Equal height columns using jQuery

A while ago I was presented with a design that was split into 3 columns all of equal height. This isn’t usually an issue but the content within the columns was going to be content managed by the client so would always be changing (or breaking). The designer was adamant that all the columns should line up across the bottom so I decided to write a quick jQuery plug-in to do this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * Simple equal height columns jQuery plugin
 * Usage: $(".col").equalCols();
 */
(function($){
    $.fn.equalCols = function(){
        //Used to sort the array
        var sortNumber = function(a,b){return b - a;};
        //Empty array
        var heights = [];
        //Save the jQuery object for manipulation at the end
        var $all = this;

        return this.each(function(i){
            var $this = $(this);
            //Push all the heights into the array
            heights.push($this.height());

            //Once we have looped through all elements
            if($.length === i){
                //Sort the array
                heights.sort(sortNumber);
                //Set all elements to the same height
                $all.css({'height': heights[0]});
            }
        });
    };
})(jQuery);

As I haven’t had much need to create custom jQuery plug-ins so far this is great practice. It also shows how easy it is to add functionality using jQuery.

The downside to this is the user will need JavaScript enabled for it to work as is always the case with client side solutions. Since the user can still see the content, even with JavaScript off I see this as no big issue.

Update: I had a comment on my Snipplr account informing me about an example given on the jQuery.map() method API page. A lot less code than what I have above but may take a few minutes to get your head around what exactly is happening.

1
2
3
4
5
6
7
8
9
$.fn.equalizeHeights = function(){
    return this.height(
        Math.max.apply(this,
            $(this).map(function(i,e){
                return $(e).height()
            }).get()
        )
    )
}
Loading

Webmentions