Jquery function to find out max height of <li>

Viewed 28263

I want to find out that out of the given <li> which li has the maximum height? how do i write such function?

If there are n <li> elements of different size, content and height. I want to figure out the maximum height of the biggest <li> element.

7 Answers

Heres a solution.

We are going to loop through the elements and find the one with the highest height.

We can make use of jquery to easily do this.

  • we will create an empty array.
  • Loop through our elements and store all the heights in this array
  • Then find the max height in that array
  • We will loop through again and set all our elements to that maximum height.

     var heights = [];
            $('.your-class-name').each(function () {
                heights.push($(this).height());
            });
            var maxHeight = Math.max.apply(null, heights);
            $('.your-class-name').each(function () {
                $(this).height(maxHeight);
            });
    

Kaboom.

$.fn.equalHeightPlugin = function () {
                        var self = this;
                        return {
                            getMaxHeight: function () {
                                let max = 0;
                                self.each(function () {
                                    if ($(this).height() > max) max = $(this).height();    
                                })
                                return max;
                            },
                            setMaxHeight: function (botOffset) {
                                let _offSet_ = 0;
                                _offSet_ = (typeof arguments[0] === "undefined") ? 0 : botOffset;                                  
                                self.height(this.getMaxHeight() + _offSet_);
                            }
                        }
                    }

You can use the above plugin to make all chosen selectors the same height.

to call the plugin if you want to set maximum height for all selectors:

var selector = $(".your-selector").equalHeightPlugin();
selector.setMaxHeight(offset);//you can have some pixels to adjust your height

If you want to get the maximum height, you can simply do this:

selector.getMaxHeight();
Related