Search code examples
bootstrap-5ruby-on-rails-7jsbundling-rails

Enable Bootstrap Tooltips in Rails 7


I am switching my Rails 7 application (which currently uses Sprockets) to using the new jsbundling+esbuild approach. I cannot get Bootstrap's tooltip functionality to work, even though I think I am following the exact instructions.

This is the dependencies node in my package.json

  "dependencies": {
    "@popperjs/core": "2.11.5",
    "bootstrap": "5.2.0",
    "esbuild": "^0.18.11",
    "jquery": "3.6.0"
  },

This is my app/javascript/application.js

window.jQuery = window.$ = require('jquery');

require('@popperjs/core');
require('bootstrap');

$('body').tooltip({
  selector: '[data-bs-toggle="tooltip"]',
});

When I load my app in Chrome I get this error:

Uncaught TypeError: $(...).tooltip is not a function

I can't see how I can debug this, since I can't tell if it's a dependency not being met or an isolation issue, or something else.


Solution

  • Bootstrap 5 no longer relies on jQuery. So the tooltips are no longer enabled via a jQuery plugin.

    You'll want to use the class based vanilla JavaScript plugin replacement.

    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl)
    })
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
    
    <button class="btn btn-primary m-2" data-bs-toggle="tooltip" title="Hello world" data-bs-placement="bottom">Bootstrap 5 Tooltip</button>

    Here is the new documentation on tooltips, and more examples.