Fixing the Intersection Observer API on CodePen
I faced a blocker while creating a quick POC using the Intersection Observer API on CodePen. And I wrote down how to fix it so you can save some time.
I guess you're already familiar with CodePen and it's stupendousness. If not, the TL;DR is: it's an online code editor that provides a super straightforward to create proof of concepts (POCs) spinning up a quick dev server and allows the ability to add known extensions and libraries such as SASS, Babel, etc.
โ๏ธ The blocker
The Intersection Observer API is practically available on every browser. So while I was writing "Scrollspying made easy with the Intersection Observer API" and trying to explain some interesting use cases I faced a blocker when trying to set up the CodePen prototype. The Intersection Observer was not working and I could not figure out why.
๐ The issue
Technically when an IntersectionObserver
gets instantiated it has some default
values within its options, nevertheless when instantiating it within the CodePen iframe
its behavior was not the expected and after a few tries I was able to detect what was happening.
๐ The fix
The default root
parameter is supposed to be "the top-level document's viewport" nevertheless as your Pen is running inside an iframe
you need to explicitly pass the document
as your default root. So the change would look something like this:
โ Before the fix
This is assuming that the need is to use the IntersectionObserver
with its default values.
const observer = new IntersectionObserver(callbackFn);
โ After the fix
This is simple one, but it definitely makes a difference:
const observer = new IntersectionObserver(callbackFn, {root: document});
๐ช Demonstration
Here you'll find the end result of a Scrollspy implementation that I explained in a previous post with the difference that I commented out the root: document
bit. As it's evident, the Scrollspy stops working as the intended configurations are not working properly.
To see how the Scrollspy ended up working please go and throw an eye on the post covering it.
Summary
Even though this looks pretty simple, I had to dedicate half an hour or maybe more to find where the issue was, so I wrote this so you don't spend that time on that weird challenge I faced. I hope this saves you some time, and of course makes you rest assured that it's not your code that's not behaving correctly (your code is perfect, right?), it's the environment where it's being run who's creating this instability.