0

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

def destroy
  flash[:danger] = "Successfuly destroyed"
  format.js
end 

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_messages
  -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(){
  $(".alert").alert('close');
});

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

VC.One
  • 14,790
  • 4
  • 25
  • 57
  • You can write the Jquery code in the `destroy.js.erb` file. And then it will work. Jquery code you need to add after `$('#flash_messages').html("` line ofcourse. Did you try this? – Arup Rakshit Jul 26 '16 at 12:15
  • That did the trick. Add it as an answer so that I can mark it as Accepted. Thank you! – Kristiyan Tsvetanov Jul 26 '16 at 12:18
  • there is some other way also to execute your code. Like executing the code when Ajax completes, from `success` callback. In that case, you don't need to put the JS inside the destroy.js.erb. But either way it will work. – Arup Rakshit Jul 26 '16 at 12:24

1 Answers1

-1

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.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317