Tuesday, February 03, 2009

Constraining elements to the browser window

I recently worked on a demo that used tooltip-like "popover" menus that appeared when the mouse pointer hovered over certain page elements. The initial approach was pretty straightforward: find the offsetTop and offsetLeft of the target element, then move the menu to those coordinates.

Two challenges:

  • If an item was too close to the left or bottom edge of the browser window, the menu would appear partially offscreen. So I had to figure out how to constrain the menu to the visible window area.
  • I had to account for any additional window scrolling.

The following seemed to do the trick. Note that this is pseudo-JavaScript; I leave it to you to figure out how to actually obtain the necessary values and make the appropriate substitutions.

// element = target element that gets the menu
// menu = the menu popover DIV

var bottomEdge = element.offsetTop + menu.height - document.scrollTop;
if ( bottomEdge > window.height )  {
    menu.top = element.offsetTop - (bottomEdge - window.height);

var leftEdge = element.offsetLeft + menu.width - document.scrollLeft;
if ( leftEdge > window.width)  {
    menu.left = element.offsetLeft - (leftEdge - window.width);