Svelte transition running function before and after

38 Views Asked by At

I have a use case where I want to expand a small image into something fullscreened.

Kind of like what is done in Example3 as shown by this repl

https://svelte.dev/repl/9b64f0fe79d84395a619f2e65771948d?version=3.42.1

However one thing I am missing is that I want it to feel like the element is being enlarged. In other words, I do not want to be able to see the original element in the background in case the enlarged element do not fully encompass the small one on the screen.

I though it would be a trivial thing to just modify the source elements opacity, but no such luck.

the best I seem to be able to do is this

https://svelte.dev/repl/d34e5606608a48af9ae08d0758f47ca4?version=3.42.1

i.e. in the css method of the svelte transition, just before returning a string I set the style of the sourceElement

sourceElement.style.opacity = "" + (1 - t);

The issue is mainly when the big element transitions back, and the source element instantly gets its opacity back without any form of smoothing.

Is there perhaps any better/smarter way of doing this?

1

There are 1 best solutions below

0
JHeth On

You can add a duration variable and set the duration of the expand transition to that. Then check the value of your selected variable and add a setTimeout whose delay is equal to the duration variable (maybe with a little offset to prevent flickering since it's images) which controls the opacity of the sourceElement.

       export let duration = 400

       return {
           duration,
           ...
           if (selected) {
                sourceElement.style.opacity = "" + (1 - t)
            } else {
                setTimeout(()=> sourceElement.style.opacity = "" + (1 - t),duration - 100)
            }
            ...
        }

Here's a remix of your REPL showing the result https://svelte.dev/repl/616a337b82594b0eb0e844acbc783cfc?version=3.42.1.