-1

My Rails app loads a partial which contains links, and a script loaded that creates onClick events for each link.

Those links render fine when then page is loaded normally (not via AJAX).

However, those onClick events aren't firing when I load the partial via AJAX.

When I do an ajax call to load_links_url, whose view contains this:

$("#my_div").html("#{j render('links/links', the_links: @links)}");

The onClick events are not firing. Why is that?

The partial links/_links.html.haml looks like this:

-links.each do |link|
    =link_to link.name, "javascript:;", id: "select_link_#{link.id}", class: "select-link", "data-id" => link.id, "data-name" => link.name

:javascript
    $(".select-link").click(function() {
        var id = $(this).data("id");
        var thename = $(this).data("name");
        $('#link_name_header').html(thename);
        $('#creative_session_link_id').val(id);
    })
bevanb
  • 8,201
  • 10
  • 53
  • 90
  • @sanka The partial file that I've pasted above renders fine when not rendered via AJAX, and the onclicks work fine. Only when it's rendered dynamically does the JS not work (the links still appear, and the JS is appended, but the onclick events don't fire). – bevanb Sep 10 '16 at 03:35
  • 1
    solution call $(".select-link").click code after dynamically adding code. – Sanka Sep 10 '16 at 03:55
  • @sanka The `$('.select-link')` code is rendered after the links themselves are rendered, if that's what you're asking. – bevanb Sep 10 '16 at 05:05
  • 1.render static element 2.execute event bind 3.add dynamic content 4.execute event bind again for dynamic added content | you are missing step 4 here. – Sanka Sep 10 '16 at 05:16
  • @sanka I see. The javascript tag is rendered dynamically too, and it appears in the DOM underneath the dynamically-rendered links. Isn't that step 4? Am I missing something? – bevanb Sep 10 '16 at 05:40
  • Even if I re-enter the `$('.select-link')` code in the console, it does not apply that to the newly created links on the page. – bevanb Sep 10 '16 at 05:46

1 Answers1

0

Have a look at the Jquery event handler not working on dynamic content

In summary, for dynamically added content, use .on with proper selector for event delegation. Like, in your case:

$('#my_div').on('click', '.select-link', function(){})
or
$(document.body).on('click', '.select-link', function(){})
Community
  • 1
  • 1
  • This isn't working unfortunately. Even if I execute this code after the HTML has been dynamically loaded, it does not work. – bevanb Sep 10 '16 at 05:51