dattebayo
dattebayo

Reputation: 2072

Finding the offset client position of an element

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?

Upvotes: 3

Views: 26465

Answers (4)

1j01
1j01

Reputation: 4180

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}

Upvotes: 0

Orhun Alp Oral
Orhun Alp Oral

Reputation: 754

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};
}

Upvotes: 4

Alex Grande
Alex Grande

Reputation: 8027

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;

Upvotes: 1

rahul
rahul

Reputation: 187030

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.

Upvotes: 3

Related Questions