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') += 10;

If I try to retrieve this value with this:
var t = document.getElementById('locator');
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 =;
var unit = x.replace(/\d/g,''); // Get unit
x = x.replace(unit,''); // Get value
if ('px' == unit) { = +x + 10 + unit; // Increment & replace unit
} else {
// If unit was anything other than px = '10px';
" value="Push me down...">