Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element offset is always 0

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.

like image 733
archon Avatar asked Dec 06 '13 21:12

archon


People also ask

What is offset of an element?

Definition and UsageThe offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.

What is element offset top?

The offsetTop property returns the top position (in pixels) relative to the parent. The returned value includes: the top position, and margin of the element. the top padding, scrollbar and border of the parent.

What is offset in angular?

Abstract. Typically, the position error of an eye-tracking device is measured as the distance of the eye-position from the target position in two-dimensional space (angular offset). Accuracy is the mean angular offset.


1 Answers

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

like image 163
John Doherty Avatar answered Oct 18 '22 09:10

John Doherty