0

So I saw a few post on this topic but non of those seems to work for me (f.e.: Jquery function doesn't work after Ajax call; JavaScript does not work after you add new elements) so I'll ask it again.

I have a little library of videos which I render with _clip_display.html.erb:

<iframe width="560" height="315" src="//www.youtube.com/embed/<%= clip_to_display %>" frameborder="0" allowfullscreen></iframe>
<% unless desc_to_display.blank? %>
    <p><%= link_to "Description", "#", remote: true, id: "desc-link" %></p>
    <span id="clip-desc">
        <%= desc_to_display %>
    </span>
<% end %>

inside of

<section class="clip">
     <%= render "clips/clip_display" %>
</section>

and I use the "Description" link to toggle the description on and off.

clips.coffee:

$(document).on "turbolinks:load", ->
  $("#desc-link").on "click", ->
    $("#clip-desc").fadeToggle()

All of which works fine until this point but if I use Ajax to remove the current video and replace it with a new one, the "Description" link does not work anymore:

$("section.clip").empty();
$("section.clip").append("<%= j render "clips/clip_display" %>");
Community
  • 1
  • 1
Bubibob
  • 181
  • 1
  • 13
  • Hi, here >>> $("section.clip").append(""); <<< you replacing server side code while you should replace rendered html (i.e. client side ) code – sr3z Sep 03 '16 at 19:10
  • [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Jonathan Lonowski Sep 03 '16 at 19:32

1 Answers1

1

You added click event to element (Description link) which is being replaced by Ajax success callback. Once the element is replaced by Ajax, bounded events will not trigger as the event is not getting initialized again. So always bind event callbacks to static parent element which can be initialized at document load. You could use something like this.

$(document).on "turbolinks:load", ->
  $("section.clip").on 'click', 'section.clip', ->
    $("#clip-desc").fadeToggle()
Sunil Antony
  • 176
  • 1
  • 9
  • Thanks, that helped a lot :). Just needed though to change $("section.clip").on 'click', 'section.clip', ... into $("section.clip").on 'click', '#desc-link', ... – Bubibob Sep 03 '16 at 19:37