Same height for elements – now with jQuery goodness!

A while ago I wrote a post on how to use the Prototype js library to make elements on your page have the same height.

For those too lazy to read that post, it can be summarised something like this:

Have a number of divs on your page that have different size blocks of text in them? Want to make all the divs have the same height, but can’t accurately determine what that height should be in advance? No problem! Use javascript to tweak the heights when the page has loaded and the browser knows the size of the divs. Use this plugin to do it automatically based on a class you supply the elements you want to change the size of. Better yet, make them all match either the smallest height or the largest height!

Simple, yes?

Well, that was with Prototype… But a while ago now I created a version for jQuery. So here it is.

/**
 * Same Height, jQuery plug-in.
 *
 * This plug-in allows you to automatically have all of the elements marked
 * with a particular class to be the same height, either by smallest or
 * largest.
 * 
 * By default, 'samemaxheight' and 'sameminheight' will be used.
 *
 * Examples of use:
 *
 *     $(document).ready(function() {
 *         $('body').sameheight();
 *     });
 *
 *     $(document).ready(function() {
 *         $('#mainContent').sameheight({
 *             max: 'mymaxclass',
 *             min: 'myminclass'
 *         });
 *     });
 *     
 *     $.fn.sameheight.defaults.max = 'mymaxclass';
 *     $.fn.sameheight.defaults.min = 'myminclass';
 *     $('body').sameheight();
 *
 * @copyright Copyright (c) 2009 Andrew Collington andy@amnuts.com
 */
(function($) {
    $.fn.sameheight = function(userOptions) {
        var options = $.extend({}, $.fn.sameheight.defaults, userOptions);

        var maxH = 0;
        $('.' + options.max, $(this)).each(function(){
            var h = $(this).height();
            maxH = (h > maxH) ? h : maxH;
        });
        $('.' + options.max, $(this)).each(function(){
            $(this).css({
                'height'   : maxH + 'px',
                'overflow' : 'hidden'
            });
        });
        
        var minH = 0;
        $('.' + options.min, $(this)).each(function(){
            var h = nodes[i].height();
            minH = ((h < minH) || !minH) ? h : minH; 
        });
        $('.' + options.min, $(this)).each(function(){
            $(this).css({
                'height'   : minH + 'px',
                'overflow' : 'hidden'
            });
        });
    };
 
    $.fn.sameheight.defaults = {
        max: 'samemaxheight',
        min: 'sameminheight'
    };
})(jQuery);
Did you like this? Share it:

One thought on “Same height for elements – now with jQuery goodness!

Leave a Reply