Thursday, November 13, 2008

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 comments:

Anonymous said...

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(){ });

Richard Hulse said...

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 CSS solution, but I have not used it.

coffey said...

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.

Richard Hulse said...

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.