Search code examples
ajaxruby-on-rails-4twitter-bootstrap-3tooltipransack

Bootstrap tooltip is not working after filtering with ajax in Rails 4


I got an index page that shows multiple objects of foo and integrated a filter function with the gem ransack and this ajax script:

$('#foo_search input').change(function(){
    $.get($('#foos_search').attr('action'), $('#foos_search').serialize(), null, "script");
    return false;
});

This is working just fine at the moment. After that I added a tooltip on each foo shown on the index page with bootstrap. JS-code looks like this:

$('[data-toggle="tooltip"]').tooltip();

Index page looks something like this:

//index.html.erb
<div id="foos">
  <%= render 'foos' %>
</div>

//_foos.html.erb
<% @foos.each do |f| %>
  <div class="btn btn-default">
    <span data-toggle="tooltip" data-html="true" data-placement="top" title="<% f.details.each do |d| %><li><%= d.name %></li><% end %>">
      DETAILS
    </span>
  </div>
<% end %>

As you can see each foo got a bunch of details and all details are supposed to show up in the tooltip. That works very well until I use my filter. As soon as I filter the foos with ransack the JS will stop working and no tooltips will show until I reload the page.

Any ideas on this?

EDIT: I uploaded the current version on heroku so maybe you could just have a look there. Since it's in German I will tell you how to get to the problem: You will see the foo objects in bright yellow jumbtrons and if you hover over "Geeignet für" for example you will see a tooltip pop up. But as soon as you use the filter function on the left the tooltip wont work anymore and will instead show some html.

https://sheltered-escarpment-6887.herokuapp.com/list

EDIT2: This is reloading the partial after changing filter options:

//index.js.erb
$("#foos").html("<%= escape_javascript(render("foos")) %>");

EDIT3: Thanks so cassioscabral I figured it out:

//index.js.erb
$("#houses").html("<%= escape_javascript(render("houses")) %>");
$('[data-toggle="tooltip"]').tooltip();

Solution

  • You should call the method $('[data-toggle="tooltip"]').tooltip(); again so it can render the tooltip again.

    I can't figure it out why your filter is affecting that. Maybe it renders(and add new dom elements) the partial after the search and since that element would be added after your initial .tooltip() call, calling again would be the right way since it's basically saying 'add the tooltip to all the elements with this data-toggle, including the new ones'