jQuery dynamic height of an element

This article describes how to set the height of an element dynamically based on the children of the element.

Normally, you would use CSS to set the height of an element, and you would expect that the element will automatically resize based on the content of the element. However, if the element’s height should automatically adapt to the height of one or many elements outside of this element, the dynaheight jQuery plugin might be handy.

Here is simple jQuery code to achieve that easily:


$.fn.dynaHeight = function(elements) {
  $(this).each(function() {
	var top = $(this).offset().top;
	var maxBottom = 0;
	$(elements).each(function() {
	  var pos = $(this).offset();
	  var height = $(this).outerHeight();
	  var bottom = pos.top + height;
	  if (bottom > maxBottom) {
	    maxBottom = bottom;
	  }
	});
    $(this).css({"height": (maxBottom - top) + "px"});
  });
  return this;
};

Example:

$(element).dynaHeight(“#item”);

As argument you pass the selector for the element that are used for determining the height.

What is it doing?

This piece of code first captures the top coordinate and then iterates through all given elements to find the max bottom coordinate. Finally it changes the CSS attribute “height”.

Download dynaheight.js.zip

Tags: , ,

Leave a Reply