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);
}

2 Comments:

At 4:41 PM, Blogger Lindsay said...

May I add a trick which proves very useful in these cases, particularly when you don't know in advance how big your popup window is going to be, perhaps because it contains flowing content.

The 'display: none' css class is commonly used to hide an element, however when it is hidden this way it does not have valid values for offsetHeight, offsetWidth etc.

If however the item is hidden instead with 'visibility: hidden' then those properties do have values, but the item is still invisible.

So if you need to know the size of something before it is visible, you can do (assuming it begins as display: none)

1) set visibility: hidden
2) remove display: none
3) check size, adjust location as needed
4) remove visibility: hidden

 
At 6:10 AM, Blogger Nick said...

I have created a tooltip system using a div tag, and yes I used "visibility: hidden" in order to make calculations before showing the tooltip.

Yes, when positioning the tooltip, the position is relative to the browser frame and not the page, so you need to calculate the offset for width and height.

My tooltip also used a "9-grid" scalable interface with borders. Because the contents of a tooltip could change, I only used one div and changed its contents.

Also, dimension variables can change from browser to browser, so there was alot of browser checking involved.

www.whatevrguild.com
www.whatevrguild.com/js/javascript.js

Was an old project I was working on, definitely expands on this concept.

 

Post a Comment

<< Home