alert("Incorrect (red): " + document.getElementById("target").getBoundingClientRect().top);
alert("Proper (blue): " + document.getElementById("wrapper").getBoundingClientRect().top);
#target {
transform: translate(20px, -20px) rotateZ(20deg);
background: red;
width: 50px;
height: 50px;
}
#wrapper {
background: blue;
display: inline-block;
}
Text
<div id="wrapper">
<div id="target">
</div>
</div>
more text
In the scenario described above, the blue square occupies the exact position that the red square would have if it did not have a transform
. It also takes up the space and location that the red square holds as an in-flow element. The JavaScript position I aim to obtain is for the blue square. The hurdle I face is that my initial code lacks a #wrapper
element which I cannot create. How do I retrieve the in-flow position of an element that may or may not be at that position (due to transform
, position: relative;
, or other factors)?
I am open to both Plain JS and jQuery solutions. However, I prefer a concise solution rather than a lengthy one exceeding 50 lines.
My attempts:
jQuery('#target').offset()
: Considers thetransform
(returns a negative value in the example above).
: Similar to jQuery'sdocument.getElementById('target').getBoundingClientRect()
offset
.jQuery('#target').position()
with traversal throughoffsetParent
: Currently functional but this aspect of jQuery may be considered a bug or subject to future changes, as per information on this site.