Skip to content
Advertisement

IntersectionObserver does not work on small screens for long sections JS

This script issues the active class for the active section. Recently noticed that it stops working on small screens. Even in the developer’s console in chrome, I will start to increase the screen size and it will appear, as soon as I start to reduce it immediately stops working (the active class disappears). But only for one long section, in the shorter ones everything works. How can this be fixed?

In the snippet, I set a large fixed height, so the portfolio link does not receive the active class, in my example, when the section width increases, its height decreases, so at some point everything starts working.

JavaScript
JavaScript
JavaScript

Advertisement

Answer

The main issue is threshold: 0.5. This tells the observer to fire once 50% of the element is visible in the viewport. For your “long” element, since its 300vh tall, and your viewport is 100vh tall, the maximum visibility that it has is 100vh/300vh = 33%, so the observer never fires.

To deal with this, you could adjust the threshold to something smaller like 0.25. That would fix the behavior for the long section, but it would make the active link change early for your shorter sections. So I propose you add 2 observers: 1 for the short sections with a threshold of 0.5 (.forJS:not(.long)), and another for the longer sections with a threshold of 0.25 (.forJS.long).

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement