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?
Add the offset of the event to the parent element offset to get the absolute offset position of the event.
An example :
When the event target is not the element which the event was registered to, it adds the offset of the parent to the current event offset in order to calculate the "Absolute" offset value.
According to Mozilla Web API: "The HTMLElement.offsetLeft read-only property returns the number of pixels that the upper left corner of the current element is offset to the left within the HTMLElement.offsetParent node."
This mostly happens when you registered an event on a parent which is containing several more children, for example: a button with an inner icon or text span, an
li
element with inner spans. etc...Sure is easy with pure JS, just do this, work for fixed and animated HTML 5 panels too, i made and try this code and it works for any brower (include IE 8):
in pure js just use
offsetLeft
andoffsetTop
properties.Example fiddle: http://jsfiddle.net/WKZ8P/
I got another Solution. Subtract parent property value from child property value
I did it like this in Internet Explorer.
=================== you can call it like this
I focus on IE only as per my focus but similar things can be done for other browsers.
Warning: jQuery, not standard JavaScript
element.offsetLeft
andelement.offsetTop
are the pure javascript properties for finding an element's position with respect to itsoffsetParent
; being the nearest parent element with a position ofrelative
orabsolute
Alternatively, you can always use Zepto to get the position of an element AND its parent, and simply subtract the two:
This has the benefit of giving you the offset of a child relative to its parent even if the parent isn't positioned.