views:

233

answers:

3

I use this script to equalize heights of elements:

(function ($) {
    $.fn.autoheight = function () {
        var height = 0,
            reset = $.browser.msie ? "1%" : "auto";
        return this.css("height", reset).each(function () {
            height = Math.max(height, this.offsetHeight);
        }).css("height", height).each(function () {
            var h = this.offsetHeight;
            if (h > height) {
                $(this).css("height", height - (h - height));
            };
        });
    };
})(jQuery);

I'd like to add just one extra functionality to it - addclass 'longest' to the longest element found when equalizing heights, what do I change in the above script?

Many thanks.

A: 

I remember stumbling across this site. Does this help? http://www.queness.com/post/126/useful-and-handy-jquery-tips-and-tricks

Read number 10. Columns of equal height.

uriDium
No, the one I'm using is perfect, I just need to addclass to the tallest element.
Nimbuz
+1  A: 

Consider this more pseudo-code than anything as it hasn't been tested (or even run). Changed code inside //new code comment

(function ($) {
    $.fn.autoheight = function () {
        var height = 0,
            highest = 0, //new code
            reset = $.browser.msie ? "1%" : "auto";
        return this.css("height", reset).each(function () {
            height = Math.max(height, this.offsetHeight);
            //new code
            if (height > highest) {
              highest = height;
              $("*").removeClass("longest");
              $(this).addClass("longest"); 
            };
            //new code
        }).css("height", height).each(function () {
            var h = this.offsetHeight;
            if (h > height) {
                $(this).css("height", height - (h - height));
            };
        });
    };
})(jQuery);
Steve Claridge
Doesn't work. :(
Nimbuz
Just checked Alex's jsFiddle example and it seems to work OK. You can inspect the result DOM using Firebug and see that one div has the 'longest' class added to it.
Steve Claridge
+2  A: 

Steve Claridge's above solution you say doesn't work - works fine for me; http://jsfiddle.net/ZqFp5/ (tested in chrome only)

Though using the

 $("*")

selector is somewhat inefficient in a large DOM, consider adding a class to the div's to use a more specific selector if possible.

 $(".foo") 
Alex
+1/2 for proving me right! and +1/2 for jsfiddle test
Steve Claridge