Skip to content

Instantly share code, notes, and snippets.

@jonrandy
Created June 11, 2024 03:21
Show Gist options
  • Save jonrandy/22d677a3cff61834e50c88392af52260 to your computer and use it in GitHub Desktop.
Save jonrandy/22d677a3cff61834e50c88392af52260 to your computer and use it in GitHub Desktop.
Observe Position Changes of an HTML Element
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