Reputation: 8382
I use ujs to send ajax request and in my destroy.js.erb file i have the following code :
$("#wrapper").prepend('<div class="flash-notice"><%= escape_javascript(flash.discard(:notice)) %></div>');
the line above show a flash-notice message when using ajax, what i want is to auto hide this flash message after a delay
( $(".flash-notice").delay(600).fadeOut(300);
) doesn't work because the message is added dynamically and not existing in the DOM
Upvotes: 1
Views: 3806
Reputation: 24815
Wrap your flash message with a div in normal html template
<div id='notice'>
</div>
Then, in js template
$('#notice').html("<%=j msg %>").show().fadeOut(4000)
The msg
method above will contain full html of <div class='flash'>...
Then, after fadeout, #notice
is still in DOM but display:none
, you can use it again anytime.
P.S. You can use a helper to process flash message so that you don't need to hard code it in template.
def flash_output(text, type)
content_tag :div, class: "flash-#{type}" do
text
end
end
So the above js template can be written to
$('#notice').html("<%=j flash_output(msg, 'notice') %>").show().fadeOut(4000)
Upvotes: 6
Reputation: 5916
An option would be to have <div class="flash-notice">
already in the dom and call something like
$(".flash-notice").html('<%= escape_javascript(flash.discard(:notice)) %>');
in your destroy.js.erb. In this way the element would already be present.
HTH
Upvotes: 1