DEV Community

Cover image for Svelte Transition and Animation
Pieces 🌟
Pieces 🌟

Posted on • Originally published at code.pieces.app

Svelte Transition and Animation

Svelte Transition and Animation.

We can all agree that adding animation and transition to web pages improves user experience. Frankly, no one really wants an ancient-looking static webpage these days. As one of the most popular JavaScript libraries, you can easily implement Svelte transition and animation without importing an external animation library. This makes animation easier and improves the performance of your application.

In this article, you will learn about Svelte animation, Svelte transition, and how to implement them in your Svelte.js application.

Prerequisites

Before we dive into implementing Svelte animations, you should be familiar with the following:

Getting Started with Svelte Transition and Animation

Let’s start by creating a new svelte.js project. You can do that by running this command in your terminal:

npx degit sveltejs/template animation-app
Enter fullscreen mode Exit fullscreen mode

This should create a Svelte.js project and install the necessary dependencies.

Implementing a Svelte Transition

In this section, we will learn to implement a transition in JS with Svelte. You can use transitions by importing them from the svelte/transition module. Let’s start by creating some static content to implement transitions:

<script>

</script>

<div>
   <h1>Pieces for Developers</h1>
   <h1>Your Workflow Copilot</h1>
   <h1>Speed up Development Time using the Pieces Copilot</h1>
  </div>
Enter fullscreen mode Exit fullscreen mode

Here, we have some static content. Now we want to apply a fade transition to it. First, we have to import the fade transition in our script tag:

<script>
import { fade } from 'svelte/transition';
</script>
Enter fullscreen mode Exit fullscreen mode

The next thing we want to do is create a button to trigger our transition. A Svelte transition can be triggered through a page load, button, or when some content arrives in the viewport. In this tutorial, our Svelte transitions will be triggered by a button. We want a button that toggles the visibility of the content. We can update the logic in our script tag:

<script>
 import { fade } from 'svelte/transition';
 let isVisible = false;

 function toggleVisibility() {
    isVisible = !isVisible;
  }
</script>
Enter fullscreen mode Exit fullscreen mode

Then create our button:

<button on:click={toggleVisibility}>Toggle content</button>
Enter fullscreen mode Exit fullscreen mode

This toggles ‘true’ or ‘false’ when the button is clicked. If the state is true, the content is shown. If the state is false, the content is hidden. The last piece of action is to apply this logic to our static content. We can do that by using the conditional #if block in Svelte:

{#if isVisible}
  <div transition:fade>
   <h1>Pieces for Developers</h1>
   <h1>Your Workflow Copilot</h1>
   <h1>Speed up Development Time using the Pieces Copilot</h1>
  </div>
{/if}
Enter fullscreen mode Exit fullscreen mode

The #if block controls the rendering of content and only shows the content if the state is true. Notice we also added a transition timing function, transition:fade, to the div tag to apply the fade transition to that particular content.

Here’s the full code:

<script>
  import { fade } from 'svelte/transition';
  let isVisible = false;

  function toggleVisibility() {
    isVisible = !isVisible;
  }
</script>

<button on:click={toggleVisibility}>Toggle content</button>

{#if isVisible}
  <div transition:fade>
   <h1>Pieces for Developers</h1>
   <h1>Your Workflow Copilot</h1>
   <h1>Speed up Development Time using the Pieces Copilot</h1>
  </div>
{/if}
Enter fullscreen mode Exit fullscreen mode

Save this code

Here’s the result of the transition:

Using a button to transition content onto the screen.

And there! The content fades in when we click on the button. By default, the fade transition has a duration of 400 milliseconds and a transition delay of 0 milliseconds. However, this can also be manually specified. Let’s see how we would apply a duration of 1200 milliseconds and a delay of 400 milliseconds:

{#if isVisible}
 <div transition:fade={{delay:400, duration:1200}}>
 <h1>Pieces for Developers</h1>
 <h1>Your Workflow Copilot</h1>
 <h1>Speed up Development Time using the Pieces Copilot</h1>
 </div>
{/if}
Enter fullscreen mode Exit fullscreen mode

In the fade attribute, we added custom properties to control the delay and duration of the transition. Let’s study the behavior:

Fading content onto a page after toggling a button.

In the above demo, we see that when the button is clicked, the content delays for a while before it comes onto the viewport. Similarly, when the button is clicked again, the content persists for a while before it leaves the viewport. This is because we manually set the values for the delay and duration. Feel free to toggle the values as you want.

Not quite sold on the fade transition JS? There are seven basic Svelte transition functions:

  1. fade
  2. fly
  3. slide
  4. blur
  5. crossfade
  6. draw
  7. scale

Let’s see how the fly transition function behaves. The fly transition function takes the x and y axis (position where you want the content to fly from and to) as parameters, as well as the duration, delay, and opacity. We can apply the fly transition to our static content:

<script>
  import { fly } from 'svelte/transition';
  let isVisible = false;

  function toggleVisibility() {
    isVisible = !isVisible;
  }
</script>

<button on:click={toggleVisibility}>Toggle content</button>

{#if isVisible}
  <div transition:fly={{x:200, y:500, delay:400, duration:1200}}>
   <h1>Pieces for Developers</h1>
   <h1>Your Workflow Copilot</h1>
   <h1>Speed up Development Time using the Pieces Copilot</h1>
  </div>
{/if}
Enter fullscreen mode Exit fullscreen mode

Here, we set the x-axis value to 100 and the y-axis to 400 and then set custom values to control the delay and duration of the Svelte transition. The expected behavior is that the content comes into the viewport from a position 200 pixels away from the original position on the x-axis and a position 500 pixels away from the original position on the y-axis. Here’s how it behaves:

Zooming content from one corner of the screen to the other.

Transition completed! There, the transition behaves as expected. Feel free to explore other Svelte transition functions in implementing visually appealing transitions.

Implementing Svelte Animation

Svelte provides a variety of animation in the svelte/animate module which is more straightforward than the transition functions. It provides a FLIP (First, Last, Invert, Play) animation function that takes in an element's start and end position and animates between them. The flip function accepts three parameters; delay, duration, and easing functions, which we are already familiar with from transitions.

Before we see how this works, let’s have an idea of what we can achieve with the flip function. Suppose we have a list of items. We can animate these items such that they “flip” or change position when a button is clicked. We start by importing flip from the svelte/animate module and writable from the svelte/store to store our items.

<script>
    import { flip } from 'svelte/animate';
    import { writable } from 'svelte/store';
</script>
Enter fullscreen mode Exit fullscreen mode

Unlike the implementation of Svelte transitions where we had to use some static content, we will save the list of items in an array so it’s easy to manipulate.

let items = writable([
        { id: 1, name: 'Pieces for Developers' },
        { id: 2, name: 'Your Workflow Copilot' },
        { id: 3, name: 'Speed up Development Time using the Pieces Copilot' }
    ]);
Enter fullscreen mode Exit fullscreen mode

Then we can create a function to handle how the content shuffles. This can be done by using the Math.random() JavaScript function, which captures the true intent of a shuffle (not being able to predict its next order of arrangement).

function shuffleItems() {
        items.update(currentItems => {
 let result = [...currentItems];
            result.sort(() => Math.random() - 0.5);
 return result;
        });
    }
Enter fullscreen mode Exit fullscreen mode

That’s all on the logic side.

Let’s implement some basic styling to make it more visually appealing.

<style>
 .item {
 padding: 10px;
 margin: 4px;
 background-color: lightblue;
 border: 1px solid blue;
 cursor: pointer;
    }
</style>
Enter fullscreen mode Exit fullscreen mode

Then we can create our button and define the animate:flip property.

<button on:click={shuffleItems}>Shuffle Items</button>
<ul>
    {#each $items as item (item.id)}
 <li animate:flip={{ duration: 300 }} class="item">
 {item.name}
 </li>
    {/each}
</ul>
Enter fullscreen mode Exit fullscreen mode

We use the #each block to render and iterate over the items defined in the array. Here’s the full code:

<script>
 import { flip } from 'svelte/animate';
 import { writable } from 'svelte/store';

 let items = writable([
        { id: 1, name: 'Pieces for Developers' },
        { id: 2, name: 'Your Workflow Copilot' },
        { id: 3, name: 'Speed up Development Time using the Pieces Copilot' }
    ]);

 function shuffleItems() {
        items.update(currentItems => {
 let result = [...currentItems];
            result.sort(() => Math.random() - 0.5);
 return result;
        });
    }
</script>

<style>
 .item {
 padding: 10px;
 margin: 4px;
 background-color: lightblue;
 border: 1px solid blue;
 cursor: pointer;
    }
</style>

<button on:click={shuffleItems}>Shuffle Items</button>
<ul>
    {#each $items as item (item.id)}
 <li animate:flip={{ duration: 300 }} class="item">
            {item.name}
 </li>
    {/each}
</ul>
Enter fullscreen mode Exit fullscreen mode

Save this code

The expected behavior of this block of code is a list of items that flips when a button is clicked. Here’s how it behaves:

Shuffling the items in a list.

Lovely! It works exactly how we want it to.

Svelte Animation x Svelte Transition x Pieces

Learning how to implement complex Svelte transitions and animations can be taxing, especially if you’re new to Svelte. There may be massive gaps in what the Svelte docs provide and the type of Svelte animation you’re looking to implement, from an ease in animation to a horizontal fade, but that’s where Pieces comes in.

With Pieces Copilot, which understands the context of your code, you can scale much higher in code complexity with ease while being guided through every bit of it. Let’s see how this works.

From the codebase we used earlier in implementing fade transitions, we can ask Pieces to create more complex transitions from that code.

Chatting with Pieces Copilot.

In the demo above, I asked the Pieces Copilot to “Modify this code such that the content comes from the right when the button is clicked”. Based on the context, Pieces Copilot immediately gives a response to that prompt, which is a code snippet that does just that. Here’s the code generated by the copilot:

<script>
 import { fly } from 'svelte/transition';
 let isVisible = false;

 function toggleVisibility() {
    isVisible = !isVisible;
  }
</script>

<button on:click={toggleVisibility}>Toggle content</button>

{#if isVisible}
 <div transition:fly="{{x: '100%', duration: 500}}">
 <h1>Pieces for Developers</h1>
 <h1>Your Workflow Copilot</h1>
 <h1>Speed up Development Time using the Pieces Copilot</h1>
 </div>
{/if}
Enter fullscreen mode Exit fullscreen mode

Here’s how it behaves:

Fading content in from the right.

The content flies into the viewport from the right, just as we as specified. You pass in the prompt or how you want the animation to behave, and Pieces handles the code. Do more while typing less.

Conclusion

In this article, you have learned about Svelte animation, Svelte transition, and how to implement more complex code with Pieces. Feel free to explore more Svelte animations and let Pieces be your ultimate guide. Good luck in your quest and happy coding!

Top comments (0)