Home Writing

til / view transitions using htmx

The View Transitions API is an experimental1 feature that adds transitions to a website, making it feel more interactive when transitioning between states or views. If you’re using Chrome, you can experience it on this website by clicking on a link from the start page or the posts page. The title of the blog post will magically “move” from the link to the header.

What’s beautiful is that htmx already supports transitions using the hx-swap attribute.

Links on this site are boosted, i.e., handled by htmx using AJAX requests. We start by adding the hx-swap attribute on the links we want to transition.

1<!-- Start page -->
2<a href="/posts/turn" hx-swap="innerHTML transition:true">
3  rotate in CSS with turn

innerHTML is the default value, but we’re telling htmx to use the modifier of transition:true with the swap, so we need to specify them both.

To tell the API what should be moved, we need to assign a unique view-transition-name to both the link and the element we want to transition to on the next page. If the name is not unique, the transition will be aborted.

1<!-- Start page -->
2<a href="/posts/turn" hx-swap="innerHTML transition:true" style="view-transition-name: turn;">
3  rotate in CSS with turn
6<!-- Post page -->
7<h1 style="view-transition-name: turn;">
8  rotate in CSS with turn

When you click the link on the start page, the title should magically transition between the two elements. We have opted to use the post’s slug as the unique identifier. We also used inline style, but CSS could have been used instead.

1<!-- Use a custom CSS property to pass the unique name -->
2<h1 style="--transition-name: turn;">
3  rotate in CSS with turn
1a, h1 {
2  view-transition-name: var(--transition-name);

  1. MDN. (2023-09-07). Browser compatibility. ↩︎

  • Loading next post...
  • Loading previous post...