Equal Height for Division (div) Elements using JavaScript

On problem I run into on a regular basis when developing web sites is that I have 2 or 3 divisions on a page that need to be the same height. This is no problem to accomplish with style sheets, just set the height property to whatever you need: height: 100px;. This becomes more difficult with dynamic text or across multiple pages. This is where JavaScript comes in handy:

function adjustHeight(elem1, elem2)
{
  var e1 = document.getElementById(elem1);
  var e2 = document.getElementById(elem2);
  if (e1 && e2)
  {
    var h1 = e1.offsetHeight;
    var h2 = e2.offsetHeight;
    if(Math.max(h1, h2) == h1)
    {
      e2.style.height = h1 + "px";
    }
    else
    {
      e1.style.height = h2 + "px";
    }
  }
}

The adjustHeight(elem1, elem2) function above takes in the id of two elements, checks to see if they actually exist, determines which element has a greater height, and sets the height of the smaller element. The offsetHeight attribute of an element is read-only (meaning we cannot assign a value to it) and returns the height of the element (including scrolling) as an integer value in pixels. We actually set the height of the element through manipulation of the elements style: e1.style.height. Theheight property must have a unit of measurement, and since offsetHeight returns pixels, we assign pixels (“px”) to the property: e2.style.height = h1 + "px";

To use this function in you code, place this script within the <head> tag of you page, being sure to identify the script as JavaScript: <script type="text/javascript">. You can then call the function using: adjustHeight("left","right"); where left and right are the elements you want equal size.

One further note: make sure this function is called after the elements have been loaded on the page. Otherwise, you will not see anything happen. One way to ensure this is putting a <script> block immediately after the elements you want resized. Another way is to attach an event to the page load that triggers the function: <body onload="adjustHeight("left","right");"> (there are better ways to attach events, this is just the simplest to write here)