Uncategorized

Equal Height Columns with jQuery

We are about to change to jQuery from Mootools, so I’m in the process of porting our current javascript functions. I’ll do a separate post later on why we are changing.

In the meantime here is the code for equal height columns:

jQuery.fn.equalHeights=function() {
var maxHeight=0;
this.each(function(){
if (this.offsetHeight>maxHeight) {maxHeight=this.offsetHeight;}
});
this.each(function(){
$(this).height(maxHeight + "px");
if (this.offsetHeight>maxHeight) {
$(this).height((maxHeight-(this.offsetHeight-maxHeight))+"px");
}
});
};

It is called like this:

$("#cont-pri,#cont-sec,#hleft,#hright,#features,#snw").equalHeights();

The jQuery function returns an object containing only the elements found, so you can include identifiers that are not on every page and the function still works. On the RNZ site there are some divs on the home page that do not appear on other pages, but require the equal heights treatment. This means the call above works on any page without generating errors.

Hat tip

4 thoughts on “Equal Height Columns with jQuery

  1. I love this and am going to use it on a site I am working on – with attribution of course. Question: I was trying to integrate the function with so that on window resize, the heights would adjust accordingly. $(window).resize(function(){ });

    Like

  2. That should work. I presume that your columns are variable width? If not, the column height is based on the tallest container of the divs specified, so it won’t change on resize.There is a < HREF="http://matthewjamestaylor.com/blog/equal-height-columns-cross-browser-css-no-hacks" REL="nofollow">CSS solution<>, but I have not used it.

    Like

  3. i have used this and have run into problems when I use show hide functionality with divs in Firefox and Chrome only. Any ideas why it’s not working I have tried clearing the content but this doesn’t work.

    Like

  4. If you start out with divs that are hidden the height of the columns will be hsort when you show something that makes them taller.

    The solution is to call equalHeights() again after you have shown the new content. It’ll recalculate the heights and you should be fine.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s