View Full Version : GetElementById not getting what I need
ScottInTexas
05-04-2003, 02:21 PM
I am trying to determine the X position of the right edge of a table cell on my page so that I can use that in positioning a div. The passed parameter does have the name of the cell (MainMenu1).
function setPos(mnu){
var mnuX=document.getElementById(mnu).style.posRight;
alert("mnu=" + mnu + " Width=" + mnuX);
}
This always returns a 0 for the x position. I have tried pixelRight, width, and a bunch of other properties that are supposed to be available.
What is wrong with this mess?
Graeme Hackston
05-04-2003, 03:23 PM
As far as I know you have to add your way to the right point of an element.
function setPos(mnu){
var el = document.getElementById(mnu)
var Mnu_Right = el.offsetLeft + el.offsetWidth
alert(Mnu_Right);
}
If the table is in another container you'll need to add it's offsetLeft.
Graeme Hackston
05-04-2003, 03:25 PM
If the <td> isn't on the left edge of the table it's offsetLeft will also need to be added
brothercake
05-04-2003, 03:31 PM
Try something like this to find the true position of an object:
function getRealPos(ele,dir)
{
(dir=="x") ? pos = ele.offsetLeft : pos = ele.offsetTop;
tempEle = ele.offsetParent;
while(tempEle != null)
{
pos += (dir=="x") ? tempEle.offsetLeft : tempEle.offsetTop;
tempEle = tempEle.offsetParent;
}
return pos;
}
Which you call with something like
var Mnu_Position = {
x : getRealPos(el,'x'),
y : getRealPos(el,'y')
};
ScottInTexas
05-04-2003, 06:10 PM
Thanks all for the answers.
It didn't explain why I couldn't get the info from the object's style, but the answer brothercake provided was just perfect for my needs. The best part about his answer was the fact that I realized I could create a type (Mnu_position) with multiple properties! I can do that in VB but didn't realize or had not remembered that I could in javascript.
Thanks Again!
brothercake
05-04-2003, 06:16 PM
Originally posted by ScottInTexas
I could create a type (Mnu_position) with multiple properties!
That's an object literal; it's the same as going:
var Mnu_Position = new Object;
Mnu_Position.x = getRealPos(el,'x');
Mnu_Position.y = getRealPos(el,'y');
Very useful indeed - as well as the code-reusability you get from OO techniques, it's also great for encapsulation, because it means you only ever need one or two global variables. No more "think of an obscure variable name so it won't clash with something else" - you can call things "menu" and "obj" and "x" and "y" with no fear :)
If you were going down that road, may as well make Mnu your master object and prototype getRealPos as a method of that.
ScottInTexas
05-04-2003, 06:49 PM
Thanks brothercake,
I'm reading up on it so I'm sure there will be some questions in the near future. I appreciate your help.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.