Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to timeout flash messages in rails

I currently have standard flash messages with the devise gem for success/failure etc. I have added the option to manually close the message with some bootstrap functionality via a close class. A small snippet is shown below.

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

I was would like to have an option to create a timeout period where the alert message would close on its one after 5 seconds. Not sure if there is a simple way to do this in Rails.

Thanks

like image 637
Stuart C Avatar asked Mar 22 '13 18:03

Stuart C


2 Answers

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>
like image 139
HungryCoder Avatar answered Nov 07 '22 21:11

HungryCoder


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;
}
like image 2
Joe McCann Avatar answered Nov 07 '22 21:11

Joe McCann