Set element’s CSS min-height using JavaScript minHeight

Recently I have been doing a lot of work on new sites that incorporate fixed-position footers (similar to the Facebook chat bar). A few examples sites are: Power Core USA and Douglas Stevens, MD (both of which I coded, graphic design by Brand Chemist). I ran into an issue with Power Core layout where the main content borders were not reaching the footer on larger displays in pages with small amounts of content (eg: not enough to activate scrollbars). So I ended up writing a quick JavaScript function to set the minHeight property of the DIVs causing the issue.

function setContentHeight() {
 if (document.getElementById) {
  var headerH = document.getElementById('headerWrapper').offsetHeight;
  var navigationH = document.getElementById('navigationWrapper').offsetHeight;
  var footerH = document.getElementById('footerWrapper').offsetHeight;
  var minH = document.body.offsetHeight - (headerH + navigationH + footerH);
  if (document.getElementById('contentLeft')) {
   var obj = document.getElementById('contentLeft');
  } else {
   var obj = document.getElementById('contentWrapper');
  }
  obj.style.minHeight = minH + 'px';
 }
}

The first thing I do with this function is make sure getElementById() is supported, otherwise there is nothing to do. On a side note, getElementById was introduced with the DOM Level 2 Specification back in 2000, so if the visitor is using a browser so old that it doesn’t support this method, why even bother? 😀

Then I get the offsetHeight of the other DIVs (or layers) in the page that affect the height. After which I get the offsetHeight of <body> and subtract the height of the other elements that are taking up vertical space.

Now that I have the “minH” value, I check to make sure “contentLeft” is defined. If I cannot find that element, I fall back to “contentWrapper” which is always available. To clarify why I perform this check, I have multiple layouts for the site in question, some pages do not have the left/right separation.

Now that we have created the “obj” variable, we set “minHeight” (the JS equivalent for CSS min-height) 🙂

Notes: “offsetHeight” always returns the measurement in pixels, so ‘px” needs to be appended to our value for correct interpretation; DOM means Document Object Model

Leave a Reply

Your email address will not be published. Required fields are marked *