« links for 2006-06-04 | Main | links for 2006-06-06 »

Position an element above the fold dynamically with JavaScript

I put together some JavaScript to keep an element above the fold.

This was written at the last minute for the Barney's New York launch; to spruce up the admin tool for their new web site. I only had time to test it in IE6 and Firefox 1.x, but I believe it works in Safari as well. Additionally, I do know that this bit of code has been in use internally at Barney's for a few months now without any complaints coming back. So it may work well on older browsers too; although I believe there are compatibility issues with document.body.clientHeight in some browsers.

Here's the pertinent bit of the example:

function aboveTheFold (someId, elTop, elHeight) {
  if (document.body.clientHeight < (elTop + elHeight)) {
    positionElOnscreen(someId, elTop, elHeight);
  }
}

function positionElOnscreen(someId, elTop, elHeight) {
  var topz= elTop;
  var heightz= elHeight;
  topz = (document.body.clientHeight - (heightz + 20));
  document.getElementById(someId).style.top = topz;
}

I call aboveTheFold from the event handler that "shows" my popup.

NOTE: The "extra" variables (topz, heightz) are a necessary workaround, see http://www.quirksmode.org/js/cross_dhtml.html.