0

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 ?

Community
  • 1
  • 1
Vital V
  • 235
  • 1
  • 4
  • 15

1 Answers1

1

You'll bind to a container element (typically document or body), and delegate the event to the to-be-created object:

$(document).on("click", "#div .link", function() {
    $(this).after("<%= insert some long view here %>");
});

Binding

As you've pointed out, JS binds events to elements of the DOM on page load

If your element is not present at load, JS won't be able to bind, thus causing a problem. To fix this, you'll have to delegate the bind to an element higher in the DOM hierarchy, allowing JS to bind the event to any new elements in relation to your container

Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • Well I have tried this, but it does not work for me. I'd like to make it clear that, in what I tried: `$("#div").on("click", ".link", function() { ` #div IS in the DOM on page load. I have also tried with `$(document).on("click", "#div .link", function() {` but still , I can't get what I want. Works from second click, but not for first – Vital V Jan 23 '14 at 13:54
  • Can I use the same function (same on click on same link) in `my_asset.js.coffee` and in `my_view.js.erb` ? Why does it work in the asset and not in the view? And what order are they executed? – Vital V Jan 23 '14 at 14:00
  • Can you post your HTML for `#div` and `.link`? – Richard Peck Jan 23 '14 at 14:25
  • Sure, this is the html for .link: `SII_1_1_Mzid_2` and tthe #div is a table (the links are created in it later, but it exists on page load ) : ` `
    – Vital V Jan 23 '14 at 15:14