1 min read

Adding close link to flash messages

Syed Aslam

The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create action that sets flash[:notice] = "Successfully created" before redirecting to a display action that can then expose the flash to its template. Actually, that exposure is automatically done.

class PostsController < ActionController::Base
  def create
    # save post
    flash[:notice] = "Post successfully created"
    redirect_to @post
  end
  def show
    # doesn't need to assign the flash notice to the template,
    # that's done automatically
  end
end
# show.html.erb
<% if flash[:notice] %>
  <div class="notice"><%= flash[:notice] %></div>
<% end %>

Image

However, we'll have to provide a way to the user to close or remove the flash message else the flash message is displayed till the view is refreshed or a new action is served.

You can employ JavaScript to automatically hide or remove the flash element from the DOM after certain time. But, you can easily add an explicit close button for users to discard flash messages:

<% flash.each do |name, msg| %>
<%= content_tag :div, :id => "flash_#{name}" do %>
  <%= msg %>
  <%= link_to_function image_tag('icons/cross.png'),
    onclick: "document.getElementById('flash_#{name}').style.display='none'" %>
  <% end %>
<% end %>
</xmp>

A little styling:

#flash_notice, #flash_error, #flash_alert {
  padding: 5px 8px;
  margin: 10px 0;
}
#flash_notice {
  background-color: #FAF0E6;
  border: solid 1px #5D871B;
  color: #5D871B;
}
#flash_error, #flash_alert {
  background-color: #FAF0E6;
  border: solid 1px #5D871B;
  color: #5D871B;
}

You need to have a image 'cross.png' in your 'images/icons'. And the outcome of is:

Image