jtomeck
jtomeck

Reputation: 179

Scrollspy using Alpinejs and intersect plugin

I have a website I'm working on that utilizes DaisyUI and Alpine.js (with intersect plugin).

In one of my templates I have a stepper with sections of content relating to each step. When you click one of the steps to the stepper, it scrolls you to the related section. That part is easy peasy. The difficulty is getting the step to highlight when you've scrolled to the related content manually. My lack of understanding of the intersection observer is what is throwing me off.

Here is a pen I made as a simple illustration of what I'm trying to do: https://codepen.io/jtomeck/pen/dyeVONz

The pen only shows the use of x-intersect alone. It works-ish, but you'll notice that there are bugs if you make the viewport taller. I'd ideally like the step to only highlight when the content is near the top of the screen, or at least more than halfway above the center of the viewport. I've tried:

  1. Using threshold, but there are bugs since it does not observe the direction (from top of viewport or bottom of viewport) the intersection is happening from, as well as the threshold being defined as a percent creates strange behaviors on different sized screens.
  2. Using margin, but it did not appear to work at all. I believe this is option is the right solution, but I'm struggling to find the proper resources online specific to my problem. I believe the answer will come if I can figure out how to manipulate the margin using enter and leave.

If someone wouldn't mind helping me with this I'd greatly appreciate it. Bonus points if all previous steps can remain highlighted when a new step is reached :). Not a requirement though!

I'd like to request that all answers continue to utilize alpinejs since it is a constraint of the project. Thank you in advance!


TLDR - Can anyone help me figure out how to use alpinejs and its intersect plugin to make the step of a stepper component highlight when the content it relates to reaches a certain position in the viewport (scrollspy effect)?


Update: Updated codepen to use:

x-intersect.margin.10%.0.0.0="shownStep = ' STEP NUMBER ID HERE '"

According to the documentation the expected behavior would be to detect intersection "when the element gets within 10% of the top of the viewport." It does not appear to work any differently than just using x-intersect without the margin added. I'm very curious why margin does seemingly nothing. I'm going to keep looking into it, but I'd very much appreciate any guidance anyone can provide about rootMargin and why the intersect plugin does not seem to be applying it properly.

Upvotes: 1

Views: 2162

Answers (0)

Related Questions