Control coordinates on screen

Discussion in 'JavaScript' started by zandor, Feb 8, 2008.

  1. #1
    Hi to all,

    my problem was to detect the coordinates for each control on the web page. Since I was not successful in finding any property to retrieve
    such information, I wrote the following code to get it out.
    The code follows at the bottom of this post.
    Basically, one calls getOBJfunction( id, "top" ) and getOBJfunction( id, "left" ) to retrieve the Y and X coordinate of the control within the
    webpage. The parameter id indicates the id property of the given control,
    according to the nomenclature used along the web page.
    Thus, for example, the position of <INPUT ID="item1"> can be
    tracked down via

    * getOBJposition( "item1", "top" );
    * getOBJposition( "item1", "left" );

    My personal use is to place floating divs over the screen and in particular below a input control where data search are performed.

    I wanted to post this message to have suggestions for further improvements.

    Thanks in advance to all checking in this topic.

    Alessandro Rosa


    function getOBJposition( id, dim )
    {
    var obj = document.getElementById( id );
    var top = 0 ; var left = 0 ;

    if ( obj != null || dim.length > 0 )
    {
    dim = dim.toLowerCase();

    while( obj.tagName.length > 0 )
    {
    if ( obj.tagName.toUpperCase() == "BODY" ) break ;

    if ( dim == "top" && obj.tagName != "TR" && obj.tagName != "TBODY" )
    {
    top += obj.offsetTop ;
    top -= obj.clientTop ;
    }
    else if ( dim == "left" && obj.tagName != "TBODY" )
    {
    left += obj.offsetLeft ;
    left -= obj.clientLeft ;
    }

    obj = obj.parentNode ;
    }

    if ( dim == "top" ) return top ;
    else if ( dim == "left" ) return left ;
    }
    else
    {
    top = left = width = height = -1 ;
    return false ;
    }
    }
     
    zandor, Feb 8, 2008 IP