Finding the offset client position of an element
-
05-07-2019 - |
Question
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?
Solution
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.
OTHER TIPS
See 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};
}
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}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow