Last Updated: February 25, 2016
·
2.604K
· brendanjcaffrey

How to use Bootstrap tooltips

In the Bootstrap documentation, it says all you have to do to get a tooltip working is add data-toggle="tooltip" and a title attribute to your HTML element. So you add it, refresh the page, and.... nothing.

What gives?

If you scroll down a little bit, you'll see "For performance reasons, the Tooltip and Popover data-apis are opt-in, meaning you must initialize them yourself." And then they give a bunch of examples where they initialize the elements by finding them by id. Not helpful.

So what's the point of the data-toggle="tooltip" attribute then? Well if you add it to a bunch of elements, and you want to initialize them all at once, you can just use this snippet:

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

$( document ).ready() makes sure that this runs after all elements in the DOM are loaded and searchable. $('[data-toggle="tooltip"]') finds all elements with a data-toggle attribute. It uses a basic CSS attribute selector (more on those here). Then finally, it just calls .tooltip() on all elements it finds to have Bootstrap initialize the tooltip.

1 Response
Add your response

Great tip!

over 1 year ago ·