Floating and Offset Javascript Values
-
26-09-2019 - |
Question
I have two items that I am floating right in my XHTML page. Unfortunately, when I try to get the offset of the right most item... it comes back as the position the element would be in if it were not floated.
<div id="Left style="float:right"></div>
<div id="right" style="float:right"></div>
Using Jquery
<script type="text/javascript">
var right = $("#right");
alert(right[0].offsetLeft);
</script>
Do I have to do something like this?
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent)
{
do
{
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
}
Solution
It looks like you are trying to find the page position.
So yes, you would use a function like:
function aGetElementsPagePosition (zElement)
{
var iLeftOffset = zElement.offsetLeft;
var iTopOffset = zElement.offsetTop;
while (zElement = zElement.offsetParent)
{
iLeftOffset += zElement.offsetLeft;
iTopOffset += zElement.offsetTop;
}
return [iLeftOffset, iTopOffset];
}
OTHER TIPS
Ended up doing this:
function findPos(obj) {
var pos = new Object();
pos.x = pos.y = 0;
if (obj.offsetParent)
{
do
{
pos.x += obj.offsetLeft;
pos.y += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return pos;
}
What I do to get the position of an element in a page, in a cross browser manner is:
var tempEl;
var myElement = document.getElementById('#someId');
//cool guys
x = myElement.offsetLeft;
y = myElement.offsetTop;
//IE 7-
if (myElement.hasLayout
&& myElement.offsetParent
&& myElement.offsetParent != document.body
) {
x = 0;
y = 0;
tempEl = myElement;
while (tempEl.parentNode) {
if (tempEl.currentStyle.hasLayout) {//very important for floated elements
x += (tempEl.offsetLeft) ? tempEl.offsetLeft : 0;
y += (tempEl.offsetTop) ? tempEl.offsetTop : 0;
}
if (tempEl == document.body) {
break;
}
tempEl = tempEl.parentNode;
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow