Retrive top value for div

N

news.west.cox.net

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.
 
R

RobG

news.west.cox.net said:
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;

Not in any browser I tested.
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.

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...">
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,481
Members
44,900
Latest member
Nell636132

Latest Threads

Top