Skip to content

Intersection Observer API #3

@lunmanlee

Description

@lunmanlee

When I was building this website I wanted the nav items to switch active states dynamically as I scroll thru each section that the nav item is linked to.

Initial solution:

  • GSAP scroll that listens to scroll events and calculate the current scroll position window.scrollY + navbarHeight
  • Loop thru all sections on the homepage to find out which one the user has gone past
  • Use getBoundingClientRect() to get each section's position
  • Set the last section we scrolled into as active

This is fine but it's more CPU intensive as there are constant position calculations and scroll events firing constantly - every pixel scrolled pass will trigger the function, it's also quite brittle, it only works when it wants to.

Then I discovered..

Intersection Observer API

Basically instead of us having to check the scroll events, it adds an Observer that observes when the target element enters or leaves the viewport (or the ancestor element) and do things. In my case, I used it to observe each section and update the corresponding nav item when that section became visible. Much more efficient and simpler 🥬

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions