Element offset is always 0

javascript, jquery

Solution

The following function walks up the DOM tree, calculating the positions on its way. It returns an object with `.x` and `.y` as properties, so `getPosition(element).y` will give you the number of pixels from the top of the page.

   /**
   * returns the absolute position of an element regardless of position/float issues
   * @param {HTMLElement} el - element to return position for 
   * @returns {object} { x: num, y: num }
   */
  function getPosition(el) {

    var x = 0,
        y = 0;

    while (el != null && (el.tagName || '').toLowerCase() != 'html') {
        x += el.offsetLeft || 0; 
        y += el.offsetTop || 0;
        el = el.parentElement;
    }

    return { x: parseInt(x, 10), y: parseInt(y, 10) };
  }

Hope this helps ;)

Problem

I am using a table with a link column when the link is clicked i would like to get the offset of the row. I tried using element.offsetTop and $(element).offset().top and both return 0 the parent elements also return 0 as their offset top. I have tried ``` function getTop(element) { var top = findPosY(element); console.log(top); } function findPosY(obj) { var curtop = 0; if (obj.offsetParent) { while (obj.offsetParent) { curtop += obj.offsetTop obj = obj.offsetParent; } } else if (obj.y) curtop += obj.y; return curtop; } ``` but this still return 0 for the y pos.

Original source