dmvvilela / svelte-scrollactive

This is a port of vue-scrollactive to Svelte, a lightweight and simple to use component that highlights menu items as you scroll the page, also scrolling to target section when clicked.
MIT License
7 stars 1 forks source link

Conflicting with other window scroll listeners. #4

Open kilianso opened 9 months ago

kilianso commented 9 months ago

Hello! Great package!

I'm experiencing conflicts with other scroll listener on the window causing an endless loop.

I'm having a navigation component that show/hides based on scrollDown or scrollUp. In this component i'm listening to scroll direction like this:

<svelte:window on:scroll={scrollHandler} bind:scrollY />

Now used together with Scrollactive on the same page, it causes an endless loop triggering scrollHandler over and over again. I also tried debouncing but it doesn't resolve the issue.

Any chance to change a setting on the scrollactive side to prevent this?

dmvvilela commented 9 months ago

The problem you're experiencing is likely due to the way JavaScript event handlers work. When you add multiple event handlers to the same event, they all get triggered when the event occurs. This is what's causing your endless loop: the scroll event is triggering both your scrollHandler and the scroll listener in the svelte-scrollactive package, which in turn triggers the scroll event again, and so on.

A potential solution to this problem could be to modify the svelte-scrollactive package to ensure that its scroll listener doesn't trigger the scroll event again. This could be achieved by using the event.stopPropagation() method, which prevents further propagation of the current event in the capturing and bubbling phases.

Another approach could be to refactor your code to use only one scroll listener that handles both the scroll direction detection and the scrollactive functionality. This would involve moving the scrollactive logic into your scrollHandler function, or vice versa. This might require a significant amount of work, depending on how complex the scrollactive logic is and how tightly it's coupled with the rest of the package's code.

About changing the package, do you mind making a PR for this? You can test if it works with your code first and I review it here.

kilianso commented 9 months ago

Thanks for the hints! I'll try to find a workaround on my end and if that doesn't help, i'll create a PR.