Best way to display flash notices in Rails

2019-03-22 04:27发布

问题:

I'm using notices in Rails and Devise and wondered what's the best way to display them?

In my application I also have it so when a user saves a post, it saves it using Ajax and I use jQuery to display a notice.

For all the notices I use:

<% flash.each do |key,msg| %>
    <div class="message" id="<%= key %>">
        <div class="message-inner">
            <%= content_tag :div, msg %>
            <a class="dismiss">x</a>
        </div>
    </div>
<% end %>

The code for that is:

$("#notice").html("Saved.");

I'd like it to be a flash notice so that it slides down from the top and after a few seconds, it slides back up again.

Since I'm using jQuery for the notice when saving a post and not using a Rails notice, it means I have to have a <div id="notice"></div> as well as the flash.each in the application.html.erb file.

Can I add it all together so I'm only using one notice and have it so it slides down from the top and then slides out of the way after a few seconds?

回答1:

I would hide the notice by default. Then call

$('#notice').html("Saved.").slideDown(500).delay(3000).slideUp(500)

You can adjust the numbers in the jQuery methods to however you want to time the animations.