I am using Ruby on Rails 4 and I would like to handle links with data-*
attributes the correct way when some HTML element is dynamically added to the DOM. That is, in my view file I have the following:
<div id="css_id">
<%= link_to("Title 1", link_path, :remote => true, "data-custom-target" => "css_id"}) %>
</div>
In my application.js
file I have:
$(function() {
$('a[data-custom-target]').on('ajax:success', function(xhr, data, status) {
css_selector = $(this).data('custom-target');
target = $("#" + css_selector);
target.replaceWith(data);
});
});
When I click on the above link then (on AJAX response success) the container div
is replaced with the following rendered code:
<div id="css_id">
<%= link_to("Title 2", link_path, :remote => true, "data-custom-target" => "css_id"}) %>
</div>
As you can see, the new rendered code contains a similar link element with the data-custom-target
attribute set. However, if I re-click on the link then the application.js
seems to not have effect as in the first case: it seems do not "bind" the $('a[data-custom-target]').on('ajax:success', ...)
to the new rendered link.
What is the problem? How can I solve that? What do you advice about?