How to initialize Tooltips in Bootstrap 4 with pure JavaScript? No jQuery

Viewed 2955

I'm somehow stuck with this code:

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

I'd like to change it to pure JavaScript. I'm not sure how to call the tooltip function, I already have some ideas like:

var tooltips = document.querySelectorAll("[data-toggle='tooltip']");
for(var i = 0; i < tooltips.length; i++){
   //this gives an error
   tooltips[i].tooltip();
}

I'm able to get all the tooltips, but I cannot initialize them. If I write something like this:

$(tooltips[i]).tooltip();

Then it works, but I want to remove the jQuery dependency since this is the only jQuery section that I have. Any idea? I've been searching and I cannot find anything useful.

2 Answers

For the new Bootstrap 5, this will be the new option without jQuery:

var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
})

More info: https://getbootstrap.com/docs/5.0/components/tooltips/

Note:

In Bootstrap 4, you cannot initialize the Tooltips without jQuery. Here is an example: https://jsfiddle.net/30c6kmnL/

There is a dependency on the function/class Tooltip that cannot be called (from my knowledge) without jQuery (you might need to rewrite the entire Tooltip function/class). I got errors like this one:

Uncaught TypeError: bootstrap.Tooltip is not a constructor

If you know how to fix it, please do it on the Snippet and share your results.

Thought I'd throw an answer out there using pure JS that also targets Bootstrap 4.x. The below code snippet will initialize all tooltips on the page in Bootstrap 4.x.

function setTooltips() {
        let tooltips = document.querySelectorAll('[data-toggle="tooltip"]');
        
        for(let i = 0; i < tooltips.length; i++) {
          let tooltip = new bootstrap.Tooltip(tooltips[i]);
        }   
      }

I'd call this in a DOMContentLoaded event globally to target any tooltips on any page.

    window.addEventListener('DOMContentLoaded', function() {
setTooltips();
}, false);

Bootstrap 5 does things differently, use Federico's answer for that which is the default way of initializing tooltips in Bootstrap 5+.

Related