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.
<!-- Start page -->
<a href="/posts/turn" hx-swap="innerHTML transition:true">
rotate in CSS with turn
</a>
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.
<!-- Start page -->
<a href="/posts/turn" hx-swap="innerHTML transition:true" style="view-transition-name: turn;">
rotate in CSS with turn
</a>
<!-- Post page -->
<h1 style="view-transition-name: turn;">
rotate in CSS with turn
</a>
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.
<!-- Use a custom CSS property to pass the unique name -->
<h1 style="--transition-name: turn;">
rotate in CSS with turn
</a>
a,
h1 {
view-transition-name: var(--transition-name);
}
-
MDN. (2023-09-07). Browser compatibility. ↩︎