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">×</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
If you've jQuery loaded in the same page, this will work for you
<div id="flash">
<a class="close" data-dismiss="alert">×</a>
<%= content_tag :div, msg, :id => "flash_#{name}" %>
</div>
<script type="text/javascript">
$(document).ready(function(){
setTimeout(function(){
$('#flash').remove();
}, 5000);
})
</script>
Using vanilla Javascript in Rails 6 (placing code in app/javascript/packs/application.js
), I used the following to fade a flash message with a '.notification'
class.
First, add a notification
class to your html. Then, in CSS, set .notification
opacity to 1 with a transition
set to ease-in-out
. Then, with JS, add the .fade
class to .notification
, which sets the opacity to 0.
JS
window.addEventListener("turbolinks:load", () => {
hideNotice();
});
function hideNotice() {
const notification = document.querySelector('.notification')
if (notification) {
setInterval(function() {
notification.classList.add('fade');
}, 5000);
}
}
CSS
.notification {
opacity: 1;
transition: opacity 0.4s ease-in-out;
}
.notification.fade {
opacity: 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With