Markus Johansson
Markus Johansson

Reputation: 3773

jQuery difference between offset().top and element.offsetTop

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.

Upvotes: 1

Views: 3219

Answers (1)

epascarello
epascarello

Reputation: 207501

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

Upvotes: 4

Related Questions