Eating Their Way Up The Corporate Ladder
A group of cannibals get appointed as engineers in a defense company. During the welcoming ceremony the boss says, "You're all part of our team now. You can earn good money here, and you can go to the cafeteria for something to eat. So please don't trouble any of the other employees." The cannibals promised.
Four weeks later the boss returns and says, "You're all working very hard, and I'm very satisfied with all of you. However, one of our janitors has disappeared. Do any of you know what happened to him?"
The cannibals all shake their heads no.
After the boss has left, the leader of the cannibals says to the others, "Which of you idiots ate the janitor?"
A hand raises hesitantly, to which the leader of the cannibals replies, "You fool! For four weeks we've been eating Team Leaders, Supervisors and Project Managers and no one noticed anything, and you have to go and eat the janitor!"
Finding the position of non-positioned elements
Another common question that gets asked in the HTML and JavaScript forum is how do I find the position of a non-positioned element. When an element is positioned absolutely on the page, it is a very easy one line statement to get the location:
var theSpotX = document.getElementById('theElement').style.top;
var theSpotY = document.getElementById('theElement').style.left;
Now with non-absolutely positioned items it is a little different. The following code allows you to find the coordinates of the element.
function GetElementPostion(xElement){
var selectedPosX = 0;
var selectedPosY = 0;
var theElement = document.getElementById(xElement);
while(theElement != null){
selectedPosX += theElement.offsetLeft;
selectedPosY += theElement.offsetTop;
theElement = theElement.offsetParent;
}
return selectedPosX + "," + selectedPosY
}
All you need to do is call the function passing the id of the element that you want the position of. The function loops through finding the position of the element that was passed. Then it loops to find the passed element's parent position. It repeats the loop until reaches the first element in the hierarchy tree of the document. By suming up all of the X and Y positions of all of the elements traversed up the document tree, you are able to find the x and y coordinates of the element of the page.
In the example code above, I am just returning a string that contains the x and y positions. You can just as easily return an array or just one of the two values depending on your need.
Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages