...

View Full Version : troubles with getting element's position



smalldog
10-15-2007, 02:27 PM
I have just a simple question.. i am wondering why the following alert is empty both in IE/FF.. dont understand why!?



<html>
<head>
<style>
body{
background-color:black;
}

#point {
width:1px;
height:1px;
background-color:red;
top:1px;
left:10px;
position:absolute;
}
</style>
</head>
<script>
function MoveDiv(){
alert(document.getElementById('point').style.top);
}
</script>
<body>
<input type="button" value="start" onclick="setInterval('MoveDiv()',3000);">
<div id="point">1</div>
</body>
</html>

Mr J
10-15-2007, 03:00 PM
document.getElementById('point').style.top will only get the position if stated inline


You can get the current position by using offsetTop

alert(document.getElementById('point').offsetTop);

or you can get the position set in the rule

var el = document.getElementById('point')

if(document.uniqueID && el.currentStyle){ // IE
elPos=el.currentStyle.top
}

if(document.defaultView && document.defaultView.getComputedStyle){
elPos=document.defaultView.getComputedStyle(el, '').getPropertyValue("top")
}

alert(elPos)

smalldog
10-15-2007, 03:06 PM
Ok, thank you, and in which documentation is described that you can get the position only of inline elements (through el.style..)? Thank you

Arbitrator
10-16-2007, 03:01 AM
I have just a simple question.. i am wondering why the following alert is empty both in IE/FF.. dont understand why!?



alert(document.getElementById('point').style.top);
…The DOM style property is a reference to the HTML/XHTML style attribute. Unless the CSS top property has been set via the style attribute, style.top will return an empty string.

To get an element’s property values regardless of the source, you should use the DOM getComputedStyle method. Internet Explorer does not support this so you must use Microsoft’s proprietary currentStyle instead for that browser.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum