Bubibob Bubibob - 3 months ago 5
Javascript Question

Javascript does not work after Ajax

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" %>");

Answer

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()
Comments