Get position/offset of element relative to a parent container?
Solution 1:
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.
Solution 2:
in pure js just use offsetLeft
and offsetTop
properties.
Example fiddle: http://jsfiddle.net/WKZ8P/
var elm = document.querySelector('span');
console.log(elm.offsetLeft, elm.offsetTop);
p { position:relative; left:10px; top:85px; border:1px solid blue; }
span{ position:relative; left:30px; top:35px; border:1px solid red; }
<p>
<span>paragraph</span>
</p>
Solution 3:
I did it like this in Internet Explorer.
function getWindowRelativeOffset(parentWindow, elem) {
var offset = {
left : 0,
top : 0
};
// relative to the target field's document
offset.left = elem.getBoundingClientRect().left;
offset.top = elem.getBoundingClientRect().top;
// now we will calculate according to the current document, this current
// document might be same as the document of target field or it may be
// parent of the document of the target field
var childWindow = elem.document.frames.window;
while (childWindow != parentWindow) {
offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
childWindow = childWindow.parent;
}
return offset;
};
=================== you can call it like this
getWindowRelativeOffset(top, inputElement);
I focus on IE only as per my focus but similar things can be done for other browsers.