Forum Moderators: open
can the getElementById method be used as a value?
i'm trying to write a script to grab the current position of an iframe and move it 10 pixels left.
This is how you get the left position of an element (NOTE: getElementById uses curved brackets, all uses square brackets):
var posLeft;
if (document.getElementById) {
posLeft = document.getElementById("myElement").style.left;
} else if (document.all) {
posLeft = document.all["myElement"].style.left;
}
Now you can change the position, and reset the property in a similar way.
HINT: if the property includes units, it will be returned as a string: "200px". You will need to parse out the numeric part, then change it, then re-add the units to make it a string again, then reset the property.
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<style type="text/css">
#test1 {top:23px;left:46px;width:20px;height:20px;background-color:blue;}
</style>
</head>
<body>
<div id="test1"></div>
<script type="text/javascript">
var posLeft;
if (document.getElementById) {
posLeft = document.getElementById("test1").style.left;
}
else if (document.all) {
posLeft = document.all["test1"].style.left;
}
alert(posLeft);
</script>
</body>
</html>
I tried the code, and sure enough nothing was returned. Then I specified the left style inline in the div tag, and the expected value was returned. But that's not what you need!
So instead of .style.left I tried .offsetLeft, and that's the solution. Be aware that offsetLeft gives the left position relative to the containing element - so if your element is nested inside another, you may also need to get the position of it's parent: you can do this with a reference to the inside element's offsetParent property.
The offset method sort of works for top, left, width, height, not for right and bottom, that's definitely better than nothing.
But, it's not that simple apparently, as I now remember after looking it up. If you take a look at Danny Goodman's 'Dynamic HTML' on O'Reilly press, chapter 9, page 472, you'll find that even this is not actually a solution due to serious cross browser discrepencies in the returned values.
So that's 4 of about 100 possible css values we can now get a sort of randomly vague existing values for, I was hoping that there was something that might actually really give the values in all cases, but I guess there isn't.