31 August 2011

Javascript - Find an elements position

To find the exact position of an element in the browser window, you'd use it's offsetLeft and offsetTop properties. These report their position relative to their parent, which you'll retrieve with the offsetParent property.

Loop through the parents adding all the offsets, and you'll end up with the absolute position of the element in question.

Javascript

This function does just that:
function findPos(element){
  var left = top = 0;
  if(element.offsetParent){
    do{
      left += element.offsetLeft;
      top += element.offsetTop;
    } while(element = element.offsetParent);
  }
  return [left, top];
}

jQuery

But then, if you're using jQuery there's an even simpler way:
var pos = element.offset();
alert(pos.left + ';' + pos.top);

No comments:

Post a Comment