Element offset is always 0

Viewed 27469

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.

5 Answers

For anyone who lands here I'd suggest to use getBoundingClientRect() to get the top and left position of an element relative to the document or to get the size of an element and its position relative to the viewport.

  var div = document.getElementById("myDiv");
  var rect = div.getBoundingClientRect();
  x = rect.left;
  y = rect.top; // how far from the top of the view port
  w = rect.width;
  h = rect.height;

I just ran into this, and the culprit was that I had added contain: content; to one of the parent elements, which apparently affects the .offsetTop values.

what John posted is good but offsetTop and offsetLeft id distance to the last relative position. this computes redundant distance. i made some changes and it works fine now:

/**
 * 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) {
  let x = 0, y = 0, n = true;

  do {
    if (n) {
      x += el.offsetLeft || 0
      y += el.offsetTop || 0
      n = false
    } else if (getComputedStyle(el).position === "relative") {
      n = true
    }
    el = el.parentElement;
  } while (el != null && (el.tagName || '').toLowerCase() !== 'html');

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