How to timeout flash messages in rails

Using vanilla Javascript in Rails 6 (placing code in app/javascript/packs/application.js), I used the following to fade a flash message with a '.notification' class.

First, add a notification class to your html. Then, in CSS, set .notification opacity to 1 with a transition set to ease-in-out. Then, with JS, add the .fade class to .notification, which sets the opacity to 0.

JS

window.addEventListener("turbolinks:load", () => {
  hideNotice();
});

function hideNotice() {
  const notification = document.querySelector('.notification')
  if (notification) {
    setInterval(function() {
      notification.classList.add('fade');
    }, 5000);
  }
}

CSS

.notification {
  opacity: 1;
  transition: opacity 0.4s ease-in-out;
}

.notification.fade {
  opacity: 0;
}

If you've jQuery loaded in the same page, this will work for you

<div id="flash">
  <a class="close" data-dismiss="alert">&#215;</a>
  <%= content_tag :div, msg, :id => "flash_#{name}" %>
</div>

<script type="text/javascript">
$(document).ready(function(){
  setTimeout(function(){
    $('#flash').remove();
  }, 5000);
 })
</script>