Search code examples
javascriptruby-on-railstwitter-bootstrapturbolinkstwitter-bootstrap-tooltip

Bootstrap tooltip persists after browser back navigation in Rails


Having some difficulty with Bootstrap tooltips, specifically getting them to hide on backwards navigation.

I'm on Rails 5 w/ Turbolinks.

Here's what happens:

  1. I click a link that has a Bootstrap tooltip
  2. The link takes me to a new page
  3. I navigate back to the original page in the browser (back button)
  4. The tooltip for the link I clicked in Step 1 is active/shown and can't be hidden

I have tried putting the tooltip on the element (an image) inside the link but the result is the same.

The JS:

$(document).on('turbolinks:load', function(event) {
  $(function () {
    $('[data-toggle="tooltip"]').tooltip()
  });
})

The rails view helper:

<%= link_to sample_path, data: { toggle: :tooltip, placement: :bottom }, title: "Title to display" do %>
  <%= image_tag "image-src-url", alt: "Alt goes here" %>
<% end %>

The HTML output:

<a data-toggle="tooltip" data-placement="bottom" title="" href="/sample-path" data-original-title="Title to display">
  <img alt="Alt goes here" src="image-src-url">
</a>

Update:

It may be an issue with clicking a link that has a tooltip on/within it. I just tried opening the link in a new tab (thus no backwards navigation, just closing the new tab), and the tooltip still remains active until a different link is clicked on the original page.


Solution

  • In this case you need to prepare you page to be cached and close the tooltip on before-cached, try this code:

    document.addEventListener("turbolinks:before-cache", function () {
        $('[data-toggle="tooltip"]').tooltip('hide');
    });
    

    I'll suggest you to read the turbolink documentation: https://github.com/turbolinks/turbolinks#preparing-the-page-to-be-cached