Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Svelte Replace element in each with both in:{...} and out:{...}

$
0
0

I have a list of elements and would like to animate when this list changes. Some items might be removed, some added, some stay the same in either the same or a different position.

My thought was that I could use a combination of Svelte's animate and in/out functions for that like so:

<script>    import { fade } from 'svelte/transition';    import { flip } from 'svelte/animate';    const listOne = ['a', 'b', 'c', 'd'];    const listTwo = ['e', 'c', 'f', 'g'];    let listIndex = $state(0);    const list = $derived(listIndex === 0 ? listOne : listTwo);    const DURATION = 3_000;    const THIRD_OF_DURATION = DURATION / 3;</script>{#each list as item (item)}<p         animate:flip={{ duration: THIRD_OF_DURATION * 3, delay: THIRD_OF_DURATION}}         in:fade={{ duration: THIRD_OF_DURATION, delay: THIRD_OF_DURATION * 2 }}         out:fade={{ duration: THIRD_OF_DURATION, delay: 0 }}>{item}</p>{/each}<button onclick={() => {    listIndex = listIndex === 0 ? 1 : 0;}}>Toggle</button>

repl

Sadly this code is not working as expected, the problem being that the new elements are added right away and move the old existing ones out of the way (they are absolutely positioned, so they could overlap).You could simplify this example even more by changing the lists to

const listOne = ['a'];const listTwo = ['b'];

and removing the animate. a and b do not get swapped, instead a is moved, vanishes and then b appears.

Any ideas how to make this work correctly?


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>