How to timeout flash messages in rails

若如初见. 提交于 2020-08-21 06:14:20

问题


I currently have standard flash messages with the devise gem for success/failure etc. I have added the option to manually close the message with some bootstrap functionality via a close class. A small snippet is shown below.

{ 
  <a class="close" data-dismiss="alert">&#215;</a>
  <%= content_tag :div, msg, :id => "flash_#{name}" %>
}

I was would like to have an option to create a timeout period where the alert message would close on its one after 5 seconds. Not sure if there is a simple way to do this in Rails.

Thanks


回答1:


If you've jQuery loaded in the same page, this will work for you

<div id="flash">
  <a class="close" data-dismiss="alert">&#215;</a>
  <%= content_tag :div, msg, :id => "flash_#{name}" %>
</div>

<script type="text/javascript">
$(document).ready(function(){
  setTimeout(function(){
    $('#flash').remove();
  }, 5000);
 })
</script>



回答2:


  1. Ensure that your div has an alert class.
  2. Add the following code in your application.js or other .js file:
$(document).on('turbolinks:load', function() {
  setTimeout(function() {
    $('.alert').fadeOut();
  }, 3000);
})

  1. Watch it go away.


来源:https://stackoverflow.com/questions/15577555/how-to-timeout-flash-messages-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!