Rails apps love flash messages. Little notes providing information, confirmation or warnings to the user. Typically implemented in a partial like so:

<% if flash[:warning] -%>
   <div id='warning'><%= flash[:warning] -%></div>
<% end -%>
<% if flash[:notice] -%>
  <div id='notice'><%= flash[:notice] -%></div>
<% end -%>

There are many cases where the message does not need to stick around for long. Consider a page with lots of AJAX interactions. Perhaps the user sends a message, which causes a page reload with a flash confirmation note (e.g. “You’re message was sent.”). After this the user will remain on the page for a relatively long time, maybe inline editing some properties or settings with AJAX tools.

It sure would be nice if that flash message would fade into the sunset after a few seconds and give back its valuable real estate, yes? Especially without forcing every flash message to disappear like Bobby Fischer.

Ask and receive, my friends. Introducing the fading_flash_message method, to be added to your nearest ApplicationController:

def fading_flash_message(text, seconds=3)
  text +
    <<-EOJS
      <script type='text/javascript'>
        Event.observe(window, 'load',function() { 
          setTimeout(function() {
            message_id = $('notice') ? 'notice' : 'warning';
            new Effect.Fade(message_id);
          }, #{seconds*1000});
        }, false);
      </script>
    EOJS
end

Setting a fading flash message in your controller is simple:

flash[:notice] = fading_flash_message("Thank you for your message.", 5)

This is change we can believe in, my friends.

Update

For Rails 3, this still works with a simple inclusion of the RawOutputHelper.

include ActionView::Helpers::RawOutputHelper
def fading_flash_message(text, seconds=3)
  raw text +
    <<-EOJS
      <script type='text/javascript'>
        Event.observe(window, 'load',function() { 
          setTimeout(function() {
            message_id = $('notice') ? 'notice' : 'warning';
            new Effect.Fade(message_id);
          }, #{seconds*1000});
        }, false);
      </script>
    EOJS
end

Oct 16, 2008 · Subscribe · Archive · Projects · Twitter · GitHub · Flickr