Right now, I have a menu which on click of a hamburger button can be expanded or collapsed. The default state of the menu is true
meaning its expanded, but when I go to a different route where the menu is not there
, it plays the collapsed animation. Here is a sample code:
<script>
import { slide } from 'svelte/transition';
let isExpanded = true;
</script>
<button on:click={()=>isExpanded=!isExpanded}>Expand/Collapse</button>
{#if isExpanded}
<nav transition:slide>
Content
</nav>
{/if}
<a href="/some-page">There is no menu in this page</a>
This is the current behavior of the code:
On page load/reload, the menu expand transition plays (weirdly, this only happens sometimes) and on clicking the link, the menu collapse transition plays for a split second while the redirect is happening.
I'm not sure if this is a bug or something wrong in my implementation. Either case, would be grateful if a workaround is provided for this.
Thanks in advance!
You can use the local
scope on the transition so it only applies when the element is created/destroyed, and not when the parent is created/destroyed.
{#if isExpanded}
<nav transition:slide|local>
Content
</nav>
{/if}
Depending on how your use case of going to a new route is implemented it may or may not work for you.
I've had mixed results with this, and there have been some bug fixes in recent versions of Svelte related to its use.
https://svelte.dev/docs/element-directives#transition-events
With Svelte 4, |local
scope is now the default for transitions.
To make them global, use |global
.