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)`;
}