Caves Travel Diving Graphics Mizar Texts Cuisine Lemkov Contact Map RSS Polski
Trybiks' Dive Texts HTML Calculating Positions of HTML Elements YAC Software
  Back

List

Charsets

Charts

DBExpress

Delphi

HTML

Intraweb

MSTest

PHP

Programming

R

Rhino Mocks

Software

Testing

UI Testing

VB.NET

VCL

WPF

Calculating Positions of HTML Elements
While developing a new site I decided to use hints (a.k.a. tooltips) that would be displayed when the user hovers the mouse pointer over some part of the page. To position the tooltip's div element, I wanted to use the following JavaScript functions:
  function tooltipFindPosX( obj )
  {
    var curLeft = 0;
    if( obj.offsetParent )
    {
      while( obj.offsetParent )
      {
        curLeft += obj.offsetLeft;
        obj = obj.offsetParent;
      }
    }
    else if( obj.x )
      curLeft = obj.x;
    return curLeft;
  }
  
  function tooltipFindPosY( obj )
  {
    var curTop = 0;
    if( obj.offsetParent )
    {
      while( obj.offsetParent )
      {
        curTop += obj.offsetTop;
        obj = obj.offsetParent;
      }
    }
    else if( obj.y )
      curTop = obj.y;
    return curTop;
  }
These functions find the position of the element next to which I wanted to show the hint. They both go through the HTML hierarchy summing up X and Y offsets of the element's parents.

This code can be found on the net, so I didn't expect any problems with it. And it does work quite nicely, except for one little problem...

Namely, in Internet Explorer, the positions were moved a bit to the right and down on some of the pages. "Nice", I thought, "that will probably take some time to fix."...

Below are example images from Firefox and IE7. The hint should be below the "Informacje" word:

Firefox:



Internet Explorer (the text being pointed to is hidden by the hint):



I searched the web, but nothing obvious came up. There were various solutions, but they seemed either to be overly complicated (for such a simple issue as this), or used arcane properties of the different browsers. When I was slowly beginning to give up, I came across this blog: Problem with offsetTop and element position location in IE.

Yay! Adding position:relative entries to offending span elements helped. Because the solution wasn't that easy to find, I include one more description here.

HTH

Top

Comments
Alas!
No comments yet...

Top

Add a comment (fields with an asterisk are required)
Name / nick *
Mail (will remain hidden) *
Your website
Comment (no tags) *
Enter the text displayed below *
 

Top

Tags

HTML


Related pages

Fix for Highslide HTML Slides

Clicking on links in JavaScript

CSS for Scrollbars on Pages and in Frames

</form> ... <form>