Hello,
Recently i faced a problem which seems very odd to me and I would like to find the answer or at least acceptable explanation. But let's go straight to it.
Let's have two divs one inside the other - the code is something like:
<div id="imgframe"> <div id="innercont" class="dragme"> <a class="marker" style="left: 1060px; top:658px;" onclick="movepos(1060, 658)"></a> </div></div><button type="button" onclick="displayattr()">Test</button>
they are styled with css like this:
#imgframe { width: 950px; height: 600px; overflow: hidden;}#innercont { width: 1994px; height: 1144px; position: relative; left: -600px; top: -300px;}
And with javascript I am trying to find the top and left values of the #innercont. I have written the following functions:
function getx() { var bg = document.getElementById("innercont"); var xs = bg.style.left; var x = Number(xs.replace("px","")); return x;}function gety() { var bg = document.getElementById("innercont"); var ys = bg.style.top; var y = Number(ys.replace("px","")); return y;}function displayattr() { var sum = getx() + ", " + gety(); alert(sum);}
Everything so far seems fine, but when I use displayattr() just after the page has been loaded it returns 0, 0. The code works fine when I use javascript to set the position of the #innercont:
function reset() { var bg = document.getElementById("innercont"); bg.style.left="-600px"; bg.style.top="-300px";}
They say that element.style.top sets or returns the top position of a positioned element, but it appears that it is not the same if we set the position by using css or javascript. So far I have managed to solve the problem by using "getComputedStyle" or adding onload="reset()" to the body tag but I don't want to use either since they mess my code later.
If anyone has an explanation why does it happen so I'll be very grateful. Thanks in advance.