Retrive top value for div

Retrive top value for div

Post by news.west. » Thu, 14 Apr 2005 03:45:02


I have a function which is called in during an onclick. The function needs
to determine the current position of a div, and act according to whether it
is currently a positive, negative or zero value.

I am able to move the div by doing the following:
document.getElementById('locator').style.top += 10;

If I try to retrieve this value with this:
var t = document.getElementById('locator').style.top;
alert(t);
But, it never shows any value, so I cannot determine its current value.

Any help is appreciated.
 
 
 

Retrive top value for div

Post by RobG » Thu, 14 Apr 2005 10:16:26


Not in any browser I tested.


If you haven't given the top property a value, it won't have one - so
it *is* showing you the current value. :-)

When setting top, it must have a unit (px, em, etc.). When changing
it, you have to allow for the units, so remove & save the units, add
the value, then replace the units.

Note that top may be set to 'auto' or percent. If you want px, then
set 'top' to some value - 0px if required.

Some play code below, lightly commented and tested in IE and Firefox.


<input type="button" style="position: relative; top: 0px;" onclick="
var x = this.style.top;
var unit = x.replace(/\d/g,''); // Get unit
x = x.replace(unit,''); // Get value
if ('px' == unit) {
this.style.top = +x + 10 + unit; // Increment & replace unit
} else {
// If unit was anything other than px
this.style.top = '10px';
}
" value="Push me down...">



--
Rob