Get position/offset of element relative to a parent container?

matt picture matt · Jul 24, 2012 · Viewed 254.4k times · Source

I'm used to working with jQuery. In my current project however I use zepto.js. Zepto doesn't provide a position() method like jQuery does. Zepto only comes with offset().

Any idea how I can retrieve the offset of a container relative to a parent with pure js or with Zepto?

Answer

jackwanders picture jackwanders · Jul 24, 2012

Warning: jQuery, not standard JavaScript

element.offsetLeft and element.offsetTop are the pure javascript properties for finding an element's position with respect to its offsetParent; being the nearest parent element with a position of relative or absolute

Alternatively, you can always use Zepto to get the position of an element AND its parent, and simply subtract the two:

var childPos = obj.offset();
var parentPos = obj.parent().offset();
var childOffset = {
    top: childPos.top - parentPos.top,
    left: childPos.left - parentPos.left
}

This has the benefit of giving you the offset of a child relative to its parent even if the parent isn't positioned.