In my Rails app, after the success of the AJAX action, a flash message appears with the message "Patient Added". Because I didn't find anywhere how to add a cross to close this message, without page reloading, I wanted to hide it automatically after 2 seconds.
What I did:
$("#add-patient").replaceWith("<%= j (render :partial => 'registrants/add_patient') %>");
$("#flash-messages").after("<div class='alert alert-success'> Patient Added </div>").fadeOut(2000);
But nothing happens, the message does not disappear nor do I get any error in the console. How to fadeout this message or at least put "x" to close it?
CodePudding user response:
You can use the jQuery delay function after the message has been displayed and before the fadeOut to delay the transition. Also, are you meaning to append the message to the flash-messages
object? As it is now, you are applying the message after the flash-messages
object, yet the fadeOut is being applied to flash-messages
. Here is a rough example of what you could do.
Note: you could also use append instead of html to add additional content to flash-messages
if there is some already existing.
$(function() {
$("#flash-messages").html("<div class='alert alert-success'> Patient Added </div>").fadeIn().delay(2000).fadeOut();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="flash-messages"></div>