1.29.2008

Another take on a jQuery.equalizeCols plugin

Using CSS, it is very difficult to create multiple columns with the same height. One must use Javascript to modify <div> height so multiple div share the same height.

This blog post offer a jQuery plugin to do that. However, this particular script cannot be applied many time to the same elements. I had to adjust the height of multiple column that have their content updated with some Ajax requests. So I needed to be able to readjust the height of the columns after the content has been updated. Using the script from the post, my column would grow after each update.

I did like how it was adjusting the height of the column. It add a div with the missing height to all the columns that needs to be adjusted.

So I came up with the following script. This script can be applied many times to the same elements without any adverse effects.

   1: jQuery.fn.equalizeCols = function() {
   2:     jQuery(this).filter(function() {return jQuery(this).find(".auto_fill").length == 0;}).each(function() {
   3:         jQuery(this).append(jQuery("<div class='auto_fill'></div>").height(0));
   4:     }).css("height", "auto");
   5:     
   6:     var max_height= 0;
   7:     jQuery(this).each(function() {
   8:         var self= jQuery(this);
   9:         var height= self.height() - self.find(".auto_fill").height();
  10:         max_height=height > max_height ? height : max_height;
  11:     });
  12:     
  13:     jQuery(this).each(function() {
  14:         var self= jQuery(this);
  15:         var height= self.height() - self.find(".auto_fill").height();
  16:         self.find(".auto_fill").height(max_height - height);
  17:     });
  18: }
 

On line 2-3, an empty <div> is added to each element that may have their height adjusted. The <div> has an initial height of 0 pixels. Note that then <div> will be added only if the containing <div> does not already have this empty <div>.

On line 6-11, the maximum height is calculated.

On line 13-17, the empty div height is adjusted so the total height of the containing div is equal to the previously calculated maximum height.

So to adjust the height of some elements, you just have to do this :

   1: $(".columns").equalizeCols();

1 comment:

RichTWebGuy said...

I realize this post is a bit old. The idea seems to work pretty well. The one problem is when one column has top/bottom padding and the other does not.

AdSense Links