181 days ago · Tech · hide · Fediverse post

Today, I wanted to show you how to detect when an element’s visibility changes using the JavaScript IntersectionObserver API. Let’s dig in! The Use Case I was recently working on a Web Component that calculates how much of the viewport it occupies, and automatically resizes itself to make sure it never overflows. As a standalone component, it worked fine. But in real-world use, it was nested inside Kelp’s toggle tabs component. When it ran it’s calculations, it was inside a [hidden] parent element, and the math was all wrong. I originally tried listening for all of the custom events emitted by Kelp components that show or hide content, but that was both error prone and not particularly sustainable. I decided to focus on detecting when the web component’s visibility changed, and learned that you can use the IntersectionObserver API for that. How It Works When an element is [hidden] (or display: none, or visiblity: hidden), even if if the hidden parent is in the viewport, the element is…

Commenting on Bubbles has been removed. Why? If you want to talk about this post, write to the author, use the comments on their blog if it has them, or reply with a "RE:" post on your own blog. Suggestions? feedback@bubbles.town