Finding the position of an offset client element
How can I find the offset client position of an element using Javascript? (I assume the same code can be written in BHO or Gecko / NPAPI).
The problem I'm running into is the way to determine the position of the biased client. e.srcElement.offsetX/Y
does not always give the correct value (same goes for clientX / Y). In some cases, we also need to consider the scrolling of the parent element.
How do we do it in general? Is there an easy way to do this?
+2
source to share
4 answers
function getElementTop ( Elem )
{
var elem;
if ( document.getElementById )
{
elem = document.getElementById ( Elem );
}
else if ( document.all )
{
elem = document.all[Elem];
}
yPos = elem.offsetTop;
tempEl = elem.offsetParent;
while ( tempEl != null )
{
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
return yPos;
}
function getElementLeft ( Elem )
{
var elem;
if ( document.getElementById )
{
var elem = document.getElementById ( Elem );
}
else if ( document.all )
{
var elem = document.all[Elem];
}
xPos = elem.offsetLeft;
tempEl = elem.offsetParent;
while ( tempEl != null )
{
xPos += tempEl.offsetLeft;
tempEl = tempEl.offsetParent;
}
return xPos;
}
Pass the id of the element to the function.
+3
source to share
To enable scrolling, look at this jQuery event listener for registering scrollTop and offset.
// Don't put this in the scroll event listener callback, or that will be unnecessarily performance intensive.
var offset = $("#id").offset().top;
$(window).bind("scroll", function() {
console.log(
$(window).scrollTop() +
offset
);
});
To get just the offset,
("#id").offset().top;
+1
source to share
CoffeeScript version of Orhun Alp Oral's answer :
getOffset = (elem)->
top = 0
left = 0
while elem
top += parseInt(elem.offsetTop)
left += parseInt(elem.offsetLeft)
elem = elem.offsetParent
{top, left}
0
source to share