Search code examples
ruby-on-railsruby-on-rails-7turbo

setting a fade to turbo_stream


Rails UJS has a compactness about it. In a single line of a js.erb file, one calls the dom_id, a partial AND gives it some interaction (that confirms the change in the object with a minimalist approach). Example with jQuery library invoked.

$("#header").html("<%= j render 'header', collection: @trecks %>").css({ opacity: 0 }).fadeTo('slow',1); 

with the goal of removing UJS and the reliance on jQuery,
What is the most succinct way to implement an equivalent in vanilla JS of .fadeTo('slow',1) on the turbo stream?


Solution

  • Issue I normally pose myself: The convention of separation of concerns...

    Why do something in JS when the presentation layer can do it? CSS.
    In fact, jQuery was invoking css; go direct!

    One can simply define the tag with a class

    <%= turbo_frame_tag dom_id(@treck), class: 'fade-text' do %>
    <% end %>
    

    with some simple CSS and get the same effect.

    .fade-text {
      animation-name: fadeIn;
      animation-duration: 3s;
      transition-timing-function: linear;
    }
    @keyframes fadeIn {
      0% {opacity:0;}
      100% {opacity:1;}
    }
    
    @-moz-keyframes fadeIn {
      0% {opacity:0;}
      100% {opacity:1;}
    }
    
    @-webkit-keyframes fadeIn {
      0% {opacity:0;}
      100% {opacity:1;}
    }
    
    @-o-keyframes fadeIn {
      0% {opacity:0;}
      100% {opacity:1;}
    }
    
    @-ms-keyframes fadeIn {
      0% {opacity:0;}
      100% {opacity:1;}
    }