tags:

views:

30

answers:

1

How to get an DOM Element [x,y] coordinates in javascript? Specifically, the coordinates of a button inside a scrollbox.

I found this offsetLeft attribute:

var elements = scroll.children; // with 12 children
if (!elements.item(2)) {
    print("no element");
}
else if (!elements.item(2).offsetLeft) {
    print("no attribute");
}
else {
    print(elements.item(2).offsetLeft);
}

but it's printing "no attribute"...

By the way, it's for Mozilla environment.

A: 

Try something like this:

// Based on code from http://www.quirksmode.org/js/findpos.html
function FindElementDocumentPosition(element) {
  var left = 0;
  var top = 0;
  var lastElement = element;
  if (element.offsetParent) {
    left += element.offsetLeft;
    top += element.offsetTop;
    element = element.offsetParent;
    while (element) {
      left += element.offsetLeft;
      top += element.offsetTop;
      left -= element.scrollLeft;
      top -= element.scrollTop;
      lastElement = element;
      element = element.offsetParent;
    }
  }
  // Adjust for document scroll position
  var agent = navigator.userAgent.toLowerCase();
  if (!PageInStandardsMode() || (agent.indexOf('firefox') == -1)) {
    var leftAdjust = document.body.scrollLeft || document.documentElement.scrollLeft;
    var topAdjust = document.body.scrollTop || document.documentElement.scrollTop;
    left += leftAdjust;
    top += topAdjust;
  }
  return {
    x: left,
    y: top
  };
}
JoshNaro
just what I said, my element don't have a offsetLeft attribute
Tom Brito
If elements.item(2).offsetLeft is zero, it will print "no attribute". You need to use "elements.item(2).offsetLeft == undefined" to determine if the attribute truly doesn't exist.
JoshNaro