Created
June 11, 2024 03:21
-
-
Save jonrandy/22d677a3cff61834e50c88392af52260 to your computer and use it in GitHub Desktop.
Observe Position Changes of an HTML Element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function observePosition(element, callback) { | |
const trackDiv = document.createElement("div") | |
Object.assign(trackDiv.style, { | |
position: "fixed", | |
pointerEvents: "none", | |
width: "2px", | |
height: "2px", | |
}) | |
if (element.children.length) { | |
element.insertBefore(trackDiv, element.firstChild) | |
} else { | |
element.appendChild(trackDiv) | |
} | |
const fixPosition = () => { | |
const rect = trackDiv.getBoundingClientRect() | |
Object.assign(trackDiv.style, { | |
marginLeft: `${parseFloat(trackDiv.style.marginLeft || "0") - rect.left - 1}px`, | |
marginTop: `${parseFloat(trackDiv.style.marginTop || "0") - rect.top - 1}px`, | |
}) | |
} | |
fixPosition() | |
const intersectionObserver = new IntersectionObserver( | |
entries => { | |
const visiblePixels = Math.round(entries[0].intersectionRatio * 4) | |
if (visiblePixels !== 1) { | |
fixPosition() | |
callback() | |
} | |
}, | |
{ threshold: [0.125, 0.375, 0.625, 0.875] } | |
) | |
intersectionObserver.observe(trackDiv) | |
return () => { | |
intersectionObserver.disconnect() | |
trackDiv.remove() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment