Neon_10 Neon_10 - 2 months ago 11
Ajax Question

js not available for ajax appeared elements in Rails

For example, I have a form field which appears with ajax request, it has class

can_be_deleted
.

<div class="form-group">
<%= f.text_field :name %>
<%= f.hidden_field :_destroy %>
<span class="fa fa-close can_be_deleted"></span>
</div>


In the same time I have some already existing elements which appear with page load, they also have class
can_be_deleted
.

<div class="form-group article_tag">
<%= f.object.name %>
<%= f.hidden_field :slug %>
<%= f.hidden_field :name %>
<%= f.hidden_field :_destroy %>
<span class="fa fa-close can_be_deleted"></span>
</div>


The coffescript which is binding when an element with this class is pressed, works for all elements EXCEPT created by ajax.

jQuery ($) ->
$(document).on "turbolinks:load", ->
$(".can_be_deleted").click ->
console.log("clicked")


How to make it working with all elements? Strange situation.

Answer

You can use ajaxComplete event, try this:

$(document).on "turbolinks:load ajaxComplete", ->   

instead this:

$(document).on "turbolinks:load", ->   
Comments