1

What is the difference between

$(this).offset().top

and

this.offsetTop

?

The element in question (this), is an img element.

I try to find the equivalent of the jQuery version.

Markus Johansson
  • 3,733
  • 8
  • 36
  • 55

1 Answers1

4

jQuery offset()

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

HTMLElement.offsetTop

offsetTop returns the distance of the current element relative to the top of the offsetParent node.

jQuery position()

Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

Getting the position of the element to the page

function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}
Community
  • 1
  • 1
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • That code example is buggy and doesn't work well in some browsers (for example Mobile Chrome on iOS). Please use this much simpler version instead: https://stackoverflow.com/a/28222246/1025702 – Matt Fletcher Jan 06 '20 at 11:13