3

I have a method that checks if an element is overflowing off screen and offsets its position so the element appears onscreen. My problem is that I need to to detect if the element changes position, because that's the event that triggers my method.

The closest thing JS offers to a native event handler is MutationObserver, however that's a bit too broad for my purposes. I only want to listen for re-positioning of specific elements. There's also the transitionend event, but that only works for elements with CSS transitions.

Is it possible to write a CustomEvent that fires only when elements are repositioned relative to the window? Or is there a native event that will do what I am trying?

Here is a sample that shows how my method works (the method works; I'm not asking for help here, just providing details):

// FETCH ELEMENT POSITION RELATIVE TO WINDOW

let positionData = el.getBoundingClientRect();

//CHECK TO SEE IF ELEMENT OVERFLOWS

if (positionData.left < 0) {
  let overflowAmount = 0 - positionData.left;

//OFFSET ELEMENT POSITION EXACTLY BY OVERFLOW AMOUNT

  el.style.transform = `translate(${overflowAmount}px, 0px)`;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jeremy Gottfried
  • 1,061
  • 13
  • 28
  • Somehow it looks like you'd need `position: fixed` for the element ..? – Teemu Jan 04 '19 at 18:32
  • No, the method works fine. The question is about how to detect repositioning of an element – Jeremy Gottfried Jan 04 '19 at 18:34
  • If MutationObservers are not to be used, I suppose only you can do is to integrate your method call with all the code and events which can change the position of the said element. – Teemu Jan 04 '19 at 18:36
  • That's a good idea, but would require a lot of code because the repositioning is not caused by the element itself. It's caused by its relative positioning to other elements. – Jeremy Gottfried Jan 04 '19 at 18:49
  • In that case a Mutation Observer begins to sound not that broad ..? – Teemu Jan 04 '19 at 18:55
  • Does this answer your question? [An event or observer for changes to getBoundingClientRect()](https://stackoverflow.com/questions/40251082/an-event-or-observer-for-changes-to-getboundingclientrect) – trusktr Dec 21 '22 at 20:58
  • Duplicate of https://stackoverflow.com/questions/40251082, which has some answers already, although more details should be added to those, along with working examples. – trusktr Dec 21 '22 at 20:58

0 Answers0