In tip #3 I showed a quick javascript tip to hide your flash messages after a time delay. This technique may not be suitable for every application however; hiding feedback messages too quickly may make your site less accessible, especially to users who are visually impaired.

Here is a technique that allows your users to hide the flash message themselves once they are finished reading it. Thus making it more accessible to users who perhaps take longer to read.

Because this technique relies on the Prototype and javascript libraries, you’ll first have to make sure to include the following in your layout:

<%= javascript_include_tag :all, :cache => true %>

Next, create a partial called “flash” in your layouts folder and include the following in your layout files:

<%= render :partial => "layouts/flash" %>

Add the following code to your _flash.html.erb template:

<%- flash.each do |name, msg| -%>
  <% content_tag :div, :class => "flash #{name}" do %>
    <p class='align_right'>
      <%= link_to_function "X", "this.parentNode.parentNode.fade({duration: 2});", :title => "close" %>
    <p><%= msg %></p>
  <% end %>
<%- end -%>

That’s all the rhtml and javascript we need to write! All that’s needed now is some CSS to style the flash box. Here is a sample of the style I’ve used:

div.flash {
  padding: 1em;
  margin: 1em;
  border-width: thin;
div.notice {
  background-color: #EFC;
  border-color: #6CB83A;
  text-align: right;

To explain what’s happening here:
Each flash message will be wrapped in a div with two classes, “flash” and also the type or key of the flash message (“error”, “warning”, “notice” etc.). The div will also have, in the top right corner, a link which, when clicked, will call the fade() javascript function on it’s parent’s parent, the flash div. I’ve named the link X so that it looks like a close button but you could change this to “close” or “hide” or anything you feel is appropriate.

The duration option is the time take in seconds for the flash div to fade out (for it’s opacity to reach 0), you can change this to whatever you prefer or leave it out completely. The default is 0.5s.

Instead of using fade() to fade the message out you could also use hide() so that the message disappears instantly or blindUp() to make it slide upwards as though it were a blind.

Written by

Photo of Gavin Morrice
Gavin Morrice

Software engineer based in Scotland

Work with me

Need help with some code?

In my free time, I like to help people improve their code and skills on Codementor.
Contact me on Codementor


Handy Rails Tips

Ruby on Rails tips and tutorials

Back to home