|
||
| Inside Technique : Interactive Tooltips : Universal Positioning Function Unfortunately getting the position of an element on the screen is not always as straightforward as you would expect. All elements expose an offsetWidth and offsetHeight property that returns a position. However, this position is not always relative to the upper-left of the screen. Instead, the rules that define the offset are fairly obscure. The offsetTop and offsetLeft properties return the element's position relative a sized or positioned element. Sized elements are tables or any element that has a defined width or height (eg., applying a CSS width to a DIV). Positioned elements are any element that has the CSS position property set to absolute or relative. Luckily, the DHTML object model in Internet Explorer exposes a property, offsetParent, that returns the element you are offset from.
You can combine this property with a simple loop to calculate an elements position from the upper-left of the document.
For example, to calculate the vertical position of an element:
We have built a generic function that extends the above function to return either the element's top or left position. This function
extends the getRealTopPos function above with an additional argument, which. The which argument takes a
string, "Top" or "Left" (case is important) and returns the element's real top or left position:
This function is fairly elegant. Rather than hard code offsetTop and offsetLeft, we dynamically look up the property value.
By recognizing that all objects in JavaScript are actually arrays, you can lookup the value of any property using
the JavaScript array notation "[]". So, our call to When working with the offsetParent property you need to be aware of a difference between IE4 and IE5's implementation. In IE4, when an element is in a table, the order of the element's offsetParents are TD, TR, TABLE, and so on. In IE5, this changed slightly and the TR is skipped. So in IE5, the order is TD, TABLE, and so on. This change has no effect on our getRealPos function but can cause problems in generic functions if you hard-code offsetParent and expect a specific element to be returned. Now, positioning an element based on another element is easy with our getRealPos function.
You merely have to set the pixelLeft and pixelTop properties of the positioned element
equal to the other element's real position.
We use this function (with a slight change shown later) to position and display the interactive tooltip. The next step is to hide the tooltip when the user is no longer over the text or the displayed tooltip. Page 1:Interactive Tooltips © 1997-2000 InsideDHTML.com, LLC. All rights reserved. |