Link to home
Start Free TrialLog in
Avatar of The_King
The_King

asked on

Getting The X and Y Absolute Position of a java applet using javascript?

How can i get the x and y co-ordinates of a java applet in javascript???


I will be using the figure to position something in javascript. Which has to be abslutely positioned but i want to position it relative to the java applet.


thanks in advance
Avatar of James Rodgers
James Rodgers
Flag of Canada image

try this, works with text boxes and such

var objTop=0;
var objLeft=0;

function getTop(obj){
      while (obj.offsetParent){
            objTop+=obj.offsetTop;
            obj=obj.offsetParent;
      }
}      

function getLeft(obj){
      while (obj.offsetParent){
            objLeft+=obj.offsetLeft;
            obj=obj.offsetParent;
      }
      
}

function getTopLeft(objGetPos){
      getLeft(objGetPos);
      getTop(objGetPos);
}      

called as getTopLeft(document.objName);
Avatar of apprenti
apprenti

I haven't used applets recently. You could try using offsetLeft and offsetTop to get the co-ordinates of the top left hand corner of the applet, if that's what you mean.
Avatar of The_King

ASKER

I keep getting the error message offsetParent is not an object
i have only ever used it with input objects, radio buttons, text, checkboxes etc.

a work around is to make a hidden/display none check box in the same tables cell or div as the applet and call the function using the radio button.
I tried that with a text box that wasnt hidden and got the same error message
ASKER CERTIFIED SOLUTION
Avatar of James Rodgers
James Rodgers
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
beware of lines like
     objTop+=obj.offsetTop;
by the DOM specs  offsetTop  (and many other properties) are not just a number. they ar a string containing a number followed by a denominator  (ie: not  200  but '200px') Netscape (and Mozilla I guess) already obey this, so you should use parseInt to get the number:
     objTop+=  parseInt( obj.offsetTop, 10 );

regards JakobA

try this, slightly different

<html>
<head>
<script language="javascript">

function getRealLeft(el)
{
    xPos = eval(el).offsetLeft;
    tempEl = eval(el).offsetParent;
      while (tempEl != null) {
           xPos += tempEl.offsetLeft;
           tempEl = tempEl.offsetParent;
      }
    return parseInt(xPos, 10);
}

function getRealTop(el) {
    yPos = eval(el).offsetTop;
    tempEl = eval(el).offsetParent;
    while (tempEl != null) {
           yPos += tempEl.offsetTop;
           tempEl = tempEl.offsetParent;
      }
    return parseInt(yPos, 10);;
}

function test(){
   
      alert(getRealLeft(divTest) + ' ' + getRealTop(divTest));
}

</script>
</head>
<body onload="test()">
<div id="divTest" style="position:absolute; top:100; left:212;">
      here is the div
</div>
</body>
</html>
thanks for the points!