Skip to content

Transitions

We can make more appealing user interfaces by gracefully transitioning elements into and out of the DOM. Solivelte makes this very easy with the transition directive.

fades in and out

Adding parameters

Transition functions can accept parameters. Let’s replace the fade transition with fly and apply it along with some options:

flies in and out

In and out

Instead of the transition directive, an element can have an inTransition or an outTransition directive, or both together. Let’s replace the transition directive with inTransition and outTransition directives:

slides in, fades out

Custom CSS transitions

Solivelte has a handful of built-in transitions, but it’s very easy to create your own. By way of example, this is the source of the fade transition:

function fade(node, { delay = 0, duration = 400 }) {
const o = +getComputedStyle(node).opacity;
return {
delay,
duration,
css: (t) => `opacity: ${t * o}`
};
}

The function takes two arguments — the node to which the transition is applied, and any parameters that were passed in — and returns a transition object which can have the following properties:

  • delay — milliseconds before the transition begins
  • duration — length of the transition in milliseconds
  • easing — a p => t easing function
  • css — a (t, u) => css function, where u === 1 - t
  • tick — a (t, u) => {...} function that has some effect on the node

The t value is 0 at the beginning of an intro or the end of an outro, and 1 at the end of an intro or beginning of an outro.

Most of the time you should return the css property and not the tick property, as CSS animations run off the main thread to prevent jank where possible. Solivelte ‘simulates’ the transition and constructs a CSS animation, then lets it run.

For example, the fade transition generates a CSS animation somewhat like this:

0% { opacity: 0 }
10% { opacity: 0.1 }
20% { opacity: 0.2 }
/* ... */
100% { opacity: 1 }

We can get a lot more creative though. Let’s make something truly gratuitous:

transitions!

Custom JS transitions

While you should generally use CSS for transitions as much as possible, there are some effects that can’t be achieved without JavaScript, such as a typewriter effect:

Solivelte

Transition events

It can be useful to know when transitions are beginning and ending. Solivelte dispatches events that you can listen to like any other DOM event:

status:

fades in and out