When modifying the height of a sticky header based on a threshold
for the yScroll
position, the animation can loop infinitely if scrolling is stopped close to the threshold, as the shrinking header itself reduces the value of yScroll
and thereby triggers it to grow again (and so on). I fixed the problem by triggering the animation only if the threshold was crossed including a buffer value.
While the code below works fine, I could not find a way to use $derived
instead of $effect
, as is recommended. Is this problem solvable using $derived
? Am I approaching the issue correctly?
<script lang="ts"> let yScroll = $state(0); let threshold = 50; let buffer = 40; let isShrunk = $state(false); $effect(() => { if (yScroll >= threshold + buffer) { isShrunk = true; } else if (yScroll <= threshold - buffer) { isShrunk = false; } });</script><svelte:window bind:scrollY={yScroll} /><header class="transition-all duration-500 {isShrunk ? 'h-16' : 'h-32'}">Header</header>