How to find the offset client position of an element using Javascript? (I assume the same code can be written in a BHO or Gecko/NPAPI).
The problem I am facing is a way to find out the offset client position of the element. The e.srcElement.offsetX/Y
does not give the correct value always (same goes for clientX/Y). In some cases we also need to consider the parent element scroll.
How do we do this in general? Is there an easy way for this?
How to find the offset client position of an element using Javascript? (I assume the same code can be written in a BHO or Gecko/NPAPI).
The problem I am facing is a way to find out the offset client position of the element. The e.srcElement.offsetX/Y
does not give the correct value always (same goes for clientX/Y). In some cases we also need to consider the parent element scroll.
How do we do this in general? Is there an easy way for this?
Share Improve this question edited Mar 4, 2013 at 0:47 ThinkingStiff 65.4k30 gold badges147 silver badges241 bronze badges asked Sep 11, 2009 at 6:47 dattebayodattebayo 2,0724 gold badges30 silver badges41 bronze badges4 Answers
Reset to default 4See the code below:
function getOffsetSum(elem) {
var top=0, left=0;
while(elem) {
top = top + parseInt(elem.offsetTop);
left = left + parseInt(elem.offsetLeft);
elem = elem.offsetParent;
}
return {top: top, left: left};
}
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 element id to the functions.
To include scrolling, take a look at this jQuery event listener to log the scrollTop and the 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 the offset alone,
("#id").offset().top;
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}