How to add animations to Hotwire's Turbo Streams

submited by
Style Pass
2024-10-06 18:00:05

Turbo Streams allow us to hook into a turbo:before-stream-render event. From here we can apply animation classes to elements that are just about to be added, or just about to be removed.

With the above snippet we can define a data-stream-enter-class and/or a data-stream-exit-class which will apply the classes we need. All of our animations can then be handled with CSS, without the need for any further custom JavaScript.

When the first ticket is added, the cart will both fade in and slide in. And when the last ticket is removed it will fade and slide out.

Next we are going to slide down any tickets that are added (unless it is the first), and slide up any that are removed (unless it is the last).

Finally, let’s add an animation for flashing the total price. It will flash green if the total increases, and red if the total decreases.

In this example we only need an “enter” animation class. However, this class needs to change based on whether the total is increased or decreased.

Leave a Comment