Back

Aug 15, 2024

Aug 15, 2024

Svelte Transition and Animation

Adding transitions and animations to your web pages is impressive and better for the user. Let’s discuss how Svelte.js and Pieces make them easy to implement.

Code in an IDE.
Code in an IDE.
Code in an IDE.

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


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>

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>

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>

Then create our button:

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

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}

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}

Save this code

Here’s the result of the transition:


Toggle Content Button shown in a browser


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}

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


Fade attribute in Svelte transition and animation.

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}

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:


Toggler Content in localhost:8080, showing an updated Svelte transition.


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>

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' }
    ]);

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;
        });
    }

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>

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>

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>

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:


List that can be shuffled with a button using Svelte animation.

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.


Using the terminal in an IDE.


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}

Here’s how it behaves:

Showing how the final web app behaves.


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!

If you're interested in learning more about Svelte and alternatives, compare Svelte vs Angular and Svelte vs React.

James Amoo headshot.
James Amoo headshot.

Written by

Written by

James Amoo

James Amoo

SHARE

SHARE

Title

Title

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.