[thelist] Getting position with Javascript without setting themin Javascript

Sheriff sheriff at drivestream.com
Sat Sep 24 14:37:02 CDT 2005


From: Peter
>I suggest PPK's article on the subject:

That article of PPK is not cross-browser (mac does not support
offsetParent)

Try mine :p, This works in any modern browser (including mac's)

// Absolute Positions
function getAbsLeft(el){
var l=el.offsetLeft;
  while((el=el.parentNode) && el!=document)
    l+=el.offsetLeft;
  return l;
}

function getAbsTop(el){
var t=el.offsetTop;
  while((el=el.parentNode) && el!=document)
    t+=el.offsetTop;
  return t;
}

// Relative Positions
function getOffLeft(el){
  return el.offsetLeft;
}

function getOffTop(el){
  return el.offsetTop;
}

From: Steve James 
[quote]
alert(document.getElementById('theNav').style.posLeft); //alerts back 

nothing/blank


However, this does:

document.getElementById('theNav').style.posLeft = '100px';

alert(document.getElementById('theNav').style.posLeft); //alerts back
100px
[/quote]
 
That's because JavaScript is a loosely typed language, so it creates the
property posLeft if it doesn't exist (posLeft is IE only). This means
the following code will also work fine:

document.getElementById('theNav').style.stevesLeft = '100px';

alert(document.getElementById('theNav').style.stevesLeft); //alerts back
100px

hehe..

whereas, 

[code] alert(document.getElementById('theNav').style.stevesLeft);
[/code] 

initially will return 'undefined'


Also, it is obvious that unless u set a property in an elements 'style'
Object the property would never get reflected. This is the same with
almost all style object properties, such as, style.color,
style.backgroundColor etc.... U can never claim why style.color doesn't
have 'black' when nothing is specified. It is simply because 'style'
always points to any 'cosmetic' u add to the element.

To access any element related property, search for a property that does
not go inside the elements style property. That's all. hehe... This is
the reason why I used el.offsetLeft - a direct property and not yet
another style related property.

Coming to your problem:

Just embed the following code inside script tags

function getAbsLeft(el){
var l=el.offsetLeft;
  while((el=el.parentNode) && el!=document)
    l+=el.offsetLeft;
  return l;
}

function getAbsTop(el){
var t=el.offsetTop;
  while((el=el.parentNode) && el!=document)
    t+=el.offsetTop;
  return t;
}

and use these as:

alert('Left: ' + getAbsLeft(document.getElementById('theNav')));
alert('Top: ' + getAbsTop(document.getElementById('theNav')));


Hope this helps! :)


Sheriff




More information about the thelist mailing list