How to positionally bind an element to another element reliably?

Viewed 31

I have a use case where I need to attach an element to a variety of HTML elements. It's important that the element be associated "with" the target element in question, for positioning purposes. For example, the below being siblings ensures that bound can likely find target and track position, or better yet, if the element is a child, I guarantee tracking. This discussion on a proposed position: element(selector) syntax highlights nicely the objective.

<!-- Okay, using element.getBoundingClientRect() + event listeners -->
<div id="container>
  <div id="target" />
</div>
<div id="tracker" />

<!-- Good, using siblings -->
<div id="container">
  <div id="target" />
  <div id="tracker" />
</div>

<!-- Better, using pseudo selectors -->
<div id="target" />
::after

<!-- Best, using children -->
<div id="target">
  <div id="tracker" />
</div>

However, the problem is not so simple across all use cases.

  • I cannot reliably control the position: absolute vs. position: relative vs. grid or flex behavior of the parent container(s). This makes it so that while tracking position is possible, inserting the tracking element may disrupt the layout.
  • Pseudo selectors like :after work nicely, however, <img /> elements cannot support a pseudo selector.
  • Not all target elements can support children, for example <img /> cannot have another <div /> embedded in them.
  • For elements that don't support children or pseudos, it is not practical to "replace" the element with a different element that does support children and or pseudos (again, due to risks of messing with the layout, breaking site behavior or bound event listeners, etc).
  • It's possible to place the tracker element outside of the target's container, and use things like targetElement.getBoundingClientRect(); to get coordinates for tracking purposes. However, the target element's container's (nested) scrolling, relative vs absolute positioning, and other behavior make targetElement.getBoundingClientRect(); unreliable without event listeners, which can be burdensome.

All that being said, are there any ways to reliably track element position for another element in this fashion?

0 Answers
Related