First of all, I tried the answers in this, and this similar questions, but that does not seem to work for me at all.
I would like to do stuff on a click event bound to an element that is created via ajax so it is not in the DOM at first.
I notice that the following coffeescript in my_asset.js.coffee
works as expected:
$ ->
$('#div').on "click", ".link", (e) ->
#do stuff
According to JQuery Doc:
this function is bound to all "selected_div" click events, even if they are added to the DOM via ajax later
And the do stuff
part works ok
However I would like to:
$(this).after("<%= insert some long view here %>")
So, in order to do that, I guess I should move the $(this).after
part from the asset.js.coffee
to my_view.js.erb
where I could embed render partial
There, in my_view.js.erb
, I have tried the following, (equivalent) javascript:
$(function() {
$("#div").on("click", ".link", function() {
$(this).after("<%= render partial here %>");
});
});
But it does not work for the first click, (it does, however, for the subsequent clicks)
I think it is related to the fact that .link
is not in the DOM when the page loads for the first time.
Why is this happening? Is that the cause? And how could I get in the view the same behaviour that I get in the asset ?