Ruby On Rails - Hotwire - Animations

Simple animations with css and stimulus

Add a CSS effect -

.effect-flash {
  animation: flash_white .8s cubic-bezier(.46,.03,.52,.96);
}

@keyframes flash_white {
  0% { background-color: #ffffff; }
  30% { background-color: #FFFF14; }
  100% { background-color: #ffffff; }
}

Create an animations controller -

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static values = { url: String }

  connect() {
    window.debug("Animations Controller Connected")
    this.removeEffect = this.removeEffect.bind(this)
    this.element.addEventListener("transitionend", this.removeEffect)
    this.element.addEventListener("animationend", this.removeEffect)
  }

  disconnect() {
    window.debug("Animations Controller Disconnected")
    this.element.removeEventListener("transitionend", this.removeEffect)
    this.element.removeEventListener("animationend", this.removeEffect)
  }

  removeEffect() {
    [...event.target.classList].reverse().forEach( (klass) => {
         if(klass.match(/^effect-/)) event.target.classList.remove(klass)
      })

  }

}
animations_controller.js

Add the controller to the page element that contains things to animate. The events bubble so you can do this on body if needed -

  <body data-controller="animations">

Simply add a class to an element, or render something with the class -

flashTarget.classList.add('effect-flash')
<tr class="effect-flash">
  <td>Name:</td>
  <td>Fred Bloggs</td>
</tr>

The animations controller clearly does very little - simply removing the class after the css animation or transition has completed.  This is important though because after navigating away from the page and then returning back, turbo would restore the page from its cache, including the animation classes, causing them to re-animate.