Any way to trigger a controller via intersectionObserver events?

I see there are many possible actions, including resize@window, but don’t see how I could trigger a controller action based on scroll-related events, like showing a “top of page” affordance after scrolling one screen height down.


Not supported out-of-the-box, but you could create a stimulus controller with your custom own intersection events. The stimulus-use library includes a userIntersection helper to make this easier to create a controller, or you could roll your own controller if you want to go lighter.

1 Like

Thank you. I’ll take a look at the source.

Update: I found waypoints and find the additional control useful. Integrated this in my project - independent from stimulusjs controllers.

Interesting, I recently rewrote all my legacy waypoints code to stimulus-use with useIntersection! :thinking::sweat_smile:

What made you go with it? It was a very good library, but it’s really old and IIRC even predates the existence of intersection observer.

UseIntersection seems to be a barebones flip switch while waypoints lets me specify direction and offset for the trigger. That was the main factor for me - didn’t spend time on deeper analysis.

Depends on your definition of barebones, I think the helper functions provide a lot of added value.

But intersection observer is by design a performant and lightweight paradigm. Waypoints uses scroll listeners under the hood, which is not lightweight, and will kill performance if you’re not careful. (I think waypoints generally did a pretty decent job with performance tweaks.)

You can still use scroll listeners with Stimulus directly, I had one waypoint that was too specific for the lightweight approach, so I put a data-action=scroll@window->controller#method on the element itself (with useThrottle to not hammer the browser since we’re listening on every scroll). This is basically what waypoints is doing, only you write the logic yourself.

I don’t mean to say that you should write every line of javascript yourself, but you should know that waypoints is 8 years old, and a lot of the code in it was written with pre-intersection observer browsers in mind.