The Cache: Technology Expert's Forum
 
*
Welcome, Guest. Please login or register. December 01, 2008, 02:19:00 PM

Login with username, password and session length


Pages: [1]
  Print  
Author Topic: Find the absolute top or left px position of an item on your HTML page  (Read 311 times)
perkiset
Olde World Hacker
Administrator
Lifer
*****
Online Online

Posts: 5211


:sniffle: Humor was so much easier before.


View Profile
« on: May 03, 2007, 05:45:27 PM »

There are many times that I want to absolutely position something, but in a relative position to something else on the page. Ergo, I need to find the top and left px value for an element I'll use as the "anchor" - but based on the way the DOM tree is laid out, I need to add together the offsets of all the parent nodes that "own" me to get the right values. Here is the code I use.

[ I'll be using this code in my Argument Against Ajax post as well... ]

Note that this expects you to pass a reference to a node, so you might use it like this:

var myElement = document.getElementById('myElement');
var top = getElementTop(myElement);

Code:
function getElementLeft(obj)
{
    var curleft = 0;
    if(obj.offsetParent)
    {
        while(true)
        {
                curleft += obj.offsetLeft;
                if(!obj.offsetParent) { break; }
                obj = obj.offsetParent;
        }
    } else if(obj.x) { curleft += obj.x; }
    return curleft;
}
function getElementTop(obj)
{
    var curtop = 0;
    if(obj.offsetParent)
    {
        while(true)
        {
                curtop += obj.offsetTop;
                if(!obj.offsetParent) { break; }
                obj = obj.offsetParent;
        }
    } else if(obj.y) { curtop += obj.y; }
    return curtop;
}
Logged

If I can't be Mr. Root then I don't want to play.
Pages: [1]
  Print  
 
Jump to:  

Perkiset's Place Home   Best of The Cache   phpMyIDE: MySQL Stored Procedures, Functions & Triggers
Politics @ Perkiset's   Pinkhat's Perspective   
cache
mart
coder
programmers
ajax
php
javascript
Powered by MySQL Powered by PHP Powered by SMF 1.1.2 | SMF © 2006-2007, Simple Machines LLC
Seo4Smf v0.2 © Webmaster's Talks


Valid XHTML 1.0! Valid CSS!