Kristiyan Tsvetanov Kristiyan Tsvetanov - 5 months ago 32
jQuery Question

Rails, remove flash message generated via ajax

I have a flash message which is generated by an ajax response.
In my controller I have:

def destroy
flash[:danger] = "Successfuly destroyed"

which calls a destroy.js.erb file

$('#flash_messages').html("<%= escape_javascript (render partial: 'layouts/flash_messages') %>");

that renders a partial which shows the flash messages. This partial looks like this:

-flash.each do |key, value|
= content_tag(:div, value, class: "flash alert alert-#{key}")

I would like to use jquery to remove the flash message after 2 seconds. What I tried was:

$(".alert").fadeTo(2000, 500).slideUp(500, function(){

which, however, does not find the .alert class because it is generated after the page load. What is a workaround this problem :? Thank you!


Your JS was loaded into the page when the actual DOM, like the <div class='alert'.. was not there. So, the binding didn't happen. 1 way to solve this, put the JS code inside the destory.js.erb file, after the file rendering logic. Another way is to execute JS code from the success callback of Ajax call for the particular element.