I’ve been trying to make the styling added to this flash message in my application layout work as desired:
<div id= "notice"><% flash.each do |key, value| %>
<%= value %>
<% end %></div>
Here’s the CSS:
#notice {
background: #e6efc2;
color: #264409;
border-color: #c6d880;
padding: 0.8em;
margin-bottom: 1em;
border: 2px solid #ddd;
}
Now the problem with this is that the flash message is rendered with ajax, and so the styling is supposed to appear only when the flash message appears. However, this is not the case. A green div appears even when there is no flash message, and this looks rather awkward.
Now I’ve tried something like this:
<div id= "notice"><% flash.each do |key, value| %>
<div class="<%= key %>"><%= value %></div>
<% end %></div>
where I use the "<%= key%>" class for styling. I leave the <div id="notice"> on the outside for the ajax rendering because it doesn’t seem to pick up the div within the ruby block. However, the CSS styling does not get rendered with the "<%= key%>" class. So it seems like i’m stuck between two bad options:
- Have an awkward green div in my app at all times that only looks how it should when the flash message is rendered or
- Not have the awkward green div, but then have no styling for the flash message so that it just looks like some awkward text.
Is there any way that I can get the best of both worlds?
Can you share your AJAX that is generating this?
One thing I would try in your situation is using jQuery’s append() method to add the flash DIV to the top of the page when the flash message is triggered, and then take it away after some timer.
–EDIT–
Here’s a “for instance” example:
Let’s just say your ajax call is hitting FoosController#Update, and is sent from the #show action.
In the show view I would have something like:
I would put your flash messages in a partial (makes the ajax code easier), so something like
views/shared/_flash.html.erb…In jQuery + ERB I would write an
update.js.erbfile in theviews/foos/Then to make it automatically fade out you could include a script (either in the specific view with flash messages or in the application.js file) like:
That would make any div.flash fade out and disappear after 5 seconds. Alternatively you could make it go away after click using the jQuery click() method.
I hope that helps.
–EDIT AGAIN–
According to this railscast, to do this with RJS:
In your view create:
In your RJS file do:
It’s still a good idea to put your flash messages in a partial. Be sure and put the flash messages in
div.flashas described in the first edit, and you should be good to go.