Bootstrap Tooltips

Learn how to use Bootstrap to generate tooltips in this lesson.


Creating the Tooltips with Bootstrap

A tooltip is a small on-screen popup that appears when a user hovers their mouse pointer over an element, like a link or button. Its purpose is to provide helpful hints or information about the element being hovered.

Using tooltips can greatly assist new website visitors as they can easily understand the icons and links by simply hovering their mouse pointer over them.

Step 1: Adding the Tooltip Markup

To add a tooltip, you need to include the data-bs-toggle=tooltip attribute within the desired element and use the title attribute to specify the text that will be displayed on hover.

For instance, the standard markup for adding a tooltip to a hyperlink is as follows:

<a href="#" data-bs-toggle="tooltip" title="Some text">Hover over me</a>

Similarly, tooltips can be applied to other elements, such as buttons and icons.

Step 2: Enabling the Tooltips

Enabling tooltips can be achieved using JavaScript by calling the tooltip() Bootstrap method with the appropriate id, class, or CSS selector of the target element.

Tooltip initialization can be done either individually or all at once. The jQuery codes below will pick all of the page's tooltips based on their data-bs-toggle attributes and initialize them all.

<script>
                    $(document).ready(function () {
                        $('[data-bs-toggle="tooltip"]').tooltip();
                    });
</script>

Note: Keep in mind that tooltip data-apis require manual initialization for performance reasons. To make sure tooltips work correctly, avoid using zero-length titles, and refrain from triggering tooltips on hidden elements.

Tip: For elements like .disabled or disabled elements, tooltips must be triggered on a wrapper element. Additionally, when tooltips are triggered from hyperlinks spanning multiple lines, they will be centered, but you can avoid this behavior by using white-space: nowrap; on such hyperlinks.


Setting the Directions of Tooltips

Tooltips can be positioned to appear on the top, right, bottom, or left sides of an element.

Positioning of Tooltips via Data Attributes

The following examples will demonstrate how to set the direction of tooltips, either through data attributes or using JavaScript.

<a href="#" data-bs-toggle="tooltip" data-bs-placement="top" title="Tooltip on top">Tooltip on top</a>
<a href="#" data-bs-toggle="tooltip" data-bs-placement="right" title="Tooltip on right">Tooltip on right</a>
<a href="#" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Tooltip on bottom">Tooltip on bottom</a>
<a href="#" data-bs-toggle="tooltip" data-bs-placement="left" title="Tooltip on left">Tooltip on left</a>

Positioning of Tooltips via JavaScript

The instance that follows will demonstrate how to use JavaScript to control the orientation of tooltips.

<script>
                    $(document).ready(function () {
                        $("#tipTop").tooltip({ placement: "top" });
                        $("#tipRight").tooltip({ placement: "right" });
                        $("#tipBottom").tooltip({ placement: "bottom" });
                        $("#tipLeft").tooltip({ placement: "left" });
                    });
</script>

Bootstrap Tooltip Options

Certain choices can be applied to the Bootstrap method tooltip() to customize the tooltip plugin's functionality.

  • Animation: Type: boolean, Value: true

    Transform the tooltip using a CSS fade transition.

  • Container: Type: string | element | false, Value: false

    Adds a tooltip to certain elements. To prevent rendering issues with complex components (e.g., input groups, button groups), specify container: 'body'.

  • Delay: Type: number | object, Value: 0

    The manual trigger type is not affected by the time delay (in milliseconds) for displaying and removing the tooltip. Delay is applied to both hiding and displaying if a number is provided. Code structure: { "show": 500, "hide": 100 }.

  • HTML: Type: boolean, Value: false

    Make a tooltip with HTML. If true, HTML tags in the tooltip's title will be shown. If false, the DOM will be filled with content using the innerText property. Use plain text if concerned about XSS attacks.

  • Placement: Type: string | function, Value: 'top'

    Specifies the tooltip's position, which can be set to 'auto', 'top', 'bottom', 'left', or 'right'. The tooltip will dynamically reorient if auto values are supplied.

  • Selector: Type: string | false, Value: false

    When a selection is given, tooltip objects are associated with the listed targets. Often used to add tooltips to dynamically inserted DOM items.

  • Template: Type: string, Value: html code

    Use this base HTML when building the tooltip. The .tooltip-inner element will get the title of the tooltip, and the tooltip's arrows will be created from the .tooltip-arrow elements. Apply the .tooltip classes to the outermost child of the wrapper's element.

  • Title: Type: string | element | function, Value: ''

    Sets the default title value in the absence of the title property.

  • Trigger: Type: string, Value: 'hover focus'

    Choose a trigger method for the tooltip: 'click', 'hover', 'focus', or 'manual'. Multiple triggers may be passed, separated by spaces. 'Manual' indicates that the tooltip will be activated programmatically using methods like .show(), .hide(), and .toggle(). This value cannot be used in conjunction with any other trigger.

  • Fallback Placements: Type: array, Value: ['top', 'right', 'bottom', 'left']

    Enables you to choose the placement that Popper will use as a backup.

  • Boundary: Type: string | element, Value: 'clippingParents'

    (Only applies to Popper's preventOverflow modifier) Tooltip overflows constraints border. May receive an HTMLElement reference through JavaScript.

  • Custom Class: Type: string | function, Value: ''

    Whenever the tooltip is displayed, add classes to it. Be aware that these classes will be included in addition to any classes listed in the templates. Use spaces to divide several classes, such as 'class1 class2'. You may also supply a function that outputs a single string of extra class names.

  • Sanitize: Type: boolean, Value: true

    Set the sanitization to on or off. If turned on, the 'template' and 'title' choices will be cleaned up.

  • Allow List: Type: object, Value: Default value

    Objects that have permissible properties and tags.

  • Sanitize Function: Type: null | function, Value: null

    Gives you the option to choose your own sanitize functions.

  • Offset: Type: array | string | function, Value: [0, 0]

    Tooltip offset in relation to its targets. Additionally, you may supply a string in data attributes with comma-separated values, such as data-bs-offset="10,20".

  • Popper Config: Type: null | object | function, Value: null

    Lets you alter the Popper configuration that comes with Bootstrap by default; see Popper's configuration.

You have the flexibility to set these choices either through data attributes or JavaScript. When using data attributes, simply add the option name preceded by data-bs- along with the desired value, like data-bs-animation=false, data-bs-placement=bottom, etc.

However, when passing options via data attributes, remember to change the case type of the option name from camelCase to kebab-case. For instance, instead of using data-bs-customClass=my-class, use data-bs-custom-class=my-class.

Nevertheless, setting options through JavaScript is the preferred method as it prevents repetitive work. You can find details on how to set tooltip options via JavaScript in the section below.


Bootstrap Tooltip Methods

The following are the standard Bootstrap tooltip methods:

Passing options

Furthermore, you can pass options to the tooltips using the options object.

For example, the following code will dynamically set the title text for the tooltips if the value of the title attribute is omitted or missing from the selected elements:

<script>
$(document).ready(function () {
    $("#myTooltip").tooltip({
        title: "It appears that the title attributes is missing."
    });
});
</script>

You can see how to insert HTML code within a tooltip by looking at the illustration below:

<script>
$(document).ready(function () {
    $("#myTooltip").tooltip({
        title: "<h4><img src='inside-tooltip.png' width='30' alt='Smiley'> Hello, <b>I'm</b> <i>Smiley!</i></h4>",
        html: true
    });
});
</script>

Another example demonstrates how to control the timing of showing and hiding the tooltip using the tooltip's delay option dynamically via JavaScript.

<script>
$(document).ready(function () {
    // Showing and hiding tooltip with same speed
    $("#tinyTooltip").tooltip({
        delay: 100 // show, hide tooltip after 100 milliseconds
    });

    // Showing and hiding tooltip with different speed
    $("#largeTooltip").tooltip({
        delay: { show: 0, hide: 2000 }
    });
});
</script>

Additionally, you can create a custom template for Bootstrap tooltips instead of using the default one, as shown in this example:

<script>
$(document).ready(function () {
    $("#myTooltip").tooltip({
        template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-head"><h3><i class="bi-info-circle"></i> Important Info</h3></div><div class="tooltip-inner"></div>'
    });
});
</script>

If you want to insert the dynamically generated HTML code of the tooltip at the end of a specific element (e.g., #wrapper) instead of the default <body> element, you can do so with JavaScript.

<script>
$(document).ready(function () {
    // Append tooltip HTML to wrapper element
    $("#myTooltip").tooltip({
        container: "#wrapper"
    });
});
</script>

Note: Remember that overriding the tooltip's default container option value may not produce a visible difference on the page. To observe the actual result, you need to inspect the DOM using developer tools or DOM Inspector.

Furthermore, there are other options available for customizing tooltips, which are detailed in the other methods of the Bootstrap tooltip plugin.

show

This approach shows the tooltip for an element. This is regarded as a "manual" trigger of the tooltip.

<script>
$(document).ready(function(){
$("#showTooltip").click(function(){
    $("#myTooltip").tooltip("show");
});
</script>

hide

The tooltip of an element is hidden using this technique. This is regarded as "manual" tooltip triggering.

<script>              
$("#hideTooltip").click(function () {
    $("#myTooltip").tooltip("hide");
    });
</script>

toggle

This technique changes the tooltip for an element. This is regarded as a "manual" tooltip triggering.

<script>       
$("#toggleTooltip").click(function () {
    $("#myTooltip").tooltip("toggle");
});
</script>

enable

The tooltip of an element can be displayed using this technique. Tooltips are automatically turned on.

<script>
$(document).ready(function(){
$("#enableTooltip").click(function(){
    $("#myTooltip").tooltip("enable");
});
</script>

disable

The ability to display a tooltip for an element is disabled by this technique. Only re-enabling the tooltip will allow it to be displayed.

<script>
$(document).ready(function(){
$("#disableTooltip").click(function(){
        $("#myTooltip").tooltip("disable");
    });
    </script>

toggleEnabled

The tooltip of an element can be displayed or hidden using this technique to toggle its visibility.

<script>
$(document).ready(function(){
$("#toggleEnabledTooltip").click(function(){
        $("#myTooltip").tooltip("toggleEnabled");
    });
    </script>

update

The tooltip of an element's location is updated using this method.

<script>
$(document).ready(function(){
$("#updateTooltip").click(function(){
        $("#myTooltip").tooltip("update");
    });
    </script>

Bootstrap Tooltip Events

The tooltip classes in Bootstrap has a limited number of events for hooking into tooltip functionalities.

  • show.bs.tooltip: When the display instances method is called, this event is instantly triggered.
  • shown.bs.tooltip: The tooltip is made visible to the users at the time that this event is fired. It won't allow itself be dismissed until the CSS transition is finished in its entirety.
  • hide.bs.tooltip: The instant the hide instances method is called, this event is fired.
  • hidden.bs.tooltip: The tooltip is no longer hidden from users when this event is initiated. It won't be fired until after the CSS transition has been finished in its entirety.
  • inserted.bs.tooltip: After the show.bs.tooltip event, which is triggered when the tooltip templates is inserted to the DOM, this event is fired.

Finally, if you want to alert the user when the fade-out transition of the tooltip is fully completed, you can use the following example to achieve that.

<script>
$(document).ready(function () {
    // Initialize tooltip
    $("#myTooltip").tooltip();

    // Show alert when the tooltip has finished being hidden 
    $("#myTooltip").on("hidden.bs.tooltip", function () {
        alert("Tooltip has been completely closed.");
    });
});
</script>

FAQ

What are Bootstrap Tooltips?

Bootstrap Tooltips are interactive pop-up messages that appear when a user hovers over or focuses on an element, such as a button, link, or icon. They provide additional context, explanations, or descriptions for the element, enhancing the user experience and improving the accessibility of your website.

How do you activate Bootstrap Tooltips?

Make sure the data-toggle attribute is set to "tooltip" and the title attribute contains the text you want to display in the tooltip. For example:

<button type="button" class="btn btn-primary" data-toggle="tooltip" title="Click me!">Hover over me</button>

Then, you'll need to initialize the tooltips using JavaScript. You can do this by adding the following script:

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

Can you customize the appearance of Bootstrap Tooltips?

Yes, you can customize the appearance of Bootstrap Tooltips using CSS. You can override the default styles by targeting the .tooltip and .tooltip-inner classes. For example, to change the background color and font color of tooltips:

.tooltip {
    background-color: #FFC107;
    color: #333;
}

.tooltip-inner {
    background-color: #FFC107;
    color: #333;
}

How can you change the tooltip's placement?

By default, Bootstrap Tooltips appear at the top of the element. You can control the placement using the data-placement attribute.

Can you use HTML content inside Bootstrap Tooltips?

Yes, you can include HTML content within Bootstrap Tooltips to create more complex and styled tooltips. To achieve this, you can set the data-html attribute to true, and then use the data-original-title attribute to store your HTML content. Keep in mind that this can potentially expose your website to cross-site scripting (XSS) vulnerabilities if you allow user-generated content. Always sanitize and validate any content before displaying it in tooltips.

<button type="button" class="btn btn-primary"
    data-toggle="tooltip" data-html="true"
    data-original-title="<em>This is</em> <strong>formatted</strong> <u>content</u>">Hover me</button>

How can you enable/disable tooltips programmatically?

You can enable or disable Bootstrap Tooltips using JavaScript. To enable tooltips, you can call the .tooltip('show') method on the element. To disable tooltips, you can call the .tooltip('hide') method. Remember to target the element using its appropriate selector.

<button id="myButton" type="button" class="btn btn-primary" data-toggle="tooltip" title="Click me!">Hover over me</button>

<script>
    $(function () {
        // Enable tooltip
        $('#myButton').tooltip('show');

        // Disable tooltip
        $('#myButton').tooltip('hide');
    });
</script>

How can you delay the display and hiding of tooltips?

You can control the delay before a tooltip appears and before it disappears using the data-delay attribute. This attribute's value should be in the format of milliseconds, with a comma separating the delay before showing and the delay before hiding.

<button type="button" class="btn btn-primary"
    data-toggle="tooltip" title="Delayed tooltip"
    data-delay="500,1000">Hover me</button>

In this example, the tooltip will appear after a delay of 500ms and disappear after a delay of 1000ms.

How can you trigger tooltips programmatically other than hover?

By default, tooltips are triggered on hover. However, you can change the trigger behavior using the data-trigger attribute. You can set its value to various options, such as "click," "focus," or "manual."

<button type="button" class="btn btn-primary"
    data-toggle="tooltip" title="Click me!"
    data-trigger="click">Click me</button>

In this example, the tooltip will appear when the button is clicked.

Can you show tooltips on disabled elements?

By default, Bootstrap Tooltips do not appear on disabled elements. However, you can enable tooltips on disabled elements by adding an extra wrapper element (such as a <span>) around the disabled element and applying the tooltip to the wrapper. This way, users can still get tooltips even on disabled elements.

<span data-toggle="tooltip" title="Tooltip on disabled element">
    <button type="button" class="btn btn-primary" disabled>Disabled Button</button>
</span>

How can you remove tooltips from an element?

To remove tooltips from an element, you can call the .tooltip('dispose') method on that element. This method removes the tooltip functionality and associated events from the element. This can be useful when you no longer need tooltips on a particular element.

<button id="myButton" type="button" class="btn btn-primary" data-toggle="tooltip" title="Tooltip to be removed">Hover over me</button>

<script>
    $(function () {
        // Dispose of the tooltip on the button
        $('#myButton').tooltip('dispose');
    });
</script>

Remember that disposing of a tooltip removes it completely, so you won't be able to re-enable it without re-initializing it.

How can you change the animation effect of tooltips?

Bootstrap Tooltips have a default fade animation. If you want to change the animation effect or disable it, you can use the data-animation attribute. Set its value to "false" to disable animations, or you can provide the animation class name for a custom effect.

<button type="button" class="btn btn-primary"
    data-toggle="tooltip" title="Tooltip with custom animation"
    data-animation="slide">Hover me</button>

In this example, the tooltip will have a sliding animation.

Can you set a maximum width for tooltips?

By default, Bootstrap Tooltips do not have a maximum width. If you want to limit the width of tooltips, you can do so using CSS by targeting the .tooltip-inner class.

.tooltip-inner {
    max-width: 200px;
}

This CSS rule limits the width of the tooltip to a maximum of 200 pixels.

How can you change the tooltip's arrow placement?

The arrow placement of Bootstrap Tooltips is automatically determined based on the tooltip's placement. If you want to customize the arrow's position, you'll need to use custom CSS. You can target the .tooltip-arrow class and adjust its positioning using the ::before pseudo-element.

.tooltip-arrow::before {
    border-top-color: red; /* Change arrow color */
    top: 10%; /* Adjust arrow's vertical position */
}

Can you have tooltips on elements other than buttons and links?

Yes, you can attach tooltips to various HTML elements, not just buttons and links. You can use tooltips with icons, images, input fields, and any other elements that can receive user interaction.

<span class="icon" data-toggle="tooltip" title="Icon Tooltip">
    <i class="fas fa-info-circle"></i>
</span>

In this example, the tooltip will appear when the user hovers over the icon.

Remember that the key is to apply the data-toggle and title attributes to the target element you want to add a tooltip to.

How can you change the default tooltip position for all tooltips?

If you want to change the default position of tooltips for all instances throughout your website, you can do so by modifying the $.fn.tooltip.Constructor.Default object properties. Here's an example to set the default tooltip position to "bottom":

$.fn.tooltip.Constructor.Default.placement = 'bottom';

Place this script after loading the Bootstrap JavaScript library, and it will affect all tooltips on your site.

How can you customize the tooltip's arrow appearance?

You can style the arrow of Bootstrap Tooltips using CSS. By default, Bootstrap uses CSS pseudo-elements to create the arrow. You can target the .tooltip-arrow class and customize its properties, such as border-color, border-width, and border-style, to change the appearance of the arrow.

.tooltip-arrow {
    border-top-color: blue;
    border-width: 8px;
    border-style: solid;
}

Can you have multiple tooltips on a single element?

No, Bootstrap does not inherently support multiple tooltips on a single element. The tooltip functionality is designed to be associated with a single title attribute per element. If you need multiple tooltips on a single element, you might need to use custom JavaScript or create a more complex setup involving popovers.

How can you prevent Bootstrap Tooltips from overflowing out of the viewport?

Sometimes tooltips can overflow outside the visible viewport, making them inaccessible. You can prevent this by setting the boundary option in the tooltip initialization. This option specifies the boundary element or viewport for the tooltip to stay within.

<button type="button" class="btn btn-primary"
    data-toggle="tooltip" title="Tooltip within the viewport"
    data-boundary="window">Hover me</button>

In this example, the tooltip will be constrained within the visible viewport.

How can you create multiline tooltips with Bootstrap?

By default, Bootstrap tooltips display as single-line text. If you want to create multiline tooltips, you can use HTML line breaks (<br>) within the title attribute. Additionally, you need to set the data-html attribute to true to allow HTML content in the tooltip.

<button type="button" class="btn btn-primary"
    data-toggle="tooltip" title="Line 1<br>Line 2"
    data-html="true">Hover me</button>

In this example, the tooltip will display two lines of content.


Conclusion

Bootstrap Tooltip stands as a robust and versatile tool that significantly enhances the user experience within web applications. Its features, such as Hover Information, Interactive Tooltip Components, and Contextual Information Display, provide an intuitive means of delivering additional details when users hover over elements, contributing to a more informative and engaging interface.

The inclusion of Tooltip Popovers and the emphasis on Tooltip Styling ensure a visually appealing and seamlessly integrated experience. The responsiveness of tooltips, exhibited through Responsive Tooltip Display and Interactive Help Popovers, allows for a consistent and user-friendly presentation across various devices.

The ability to customize tooltips with Tooltip Customization Options and integrate Dynamic Content Tooltip provides developers with the flexibility to tailor these informational elements to meet specific design requirements. Features like Display Tooltip with Delay and Show tooltip after 2 seconds contribute to refined user interactions, allowing for intentional and well-timed information presentation.

Bootstrap Tooltip further excels in providing precise control over positioning, directional orientation, and overall styling, evident in Tooltip Positioning, Configure Tooltip Directions, Placement Settings, and Tooltip Orientation Options. The dynamic nature of the tooltips is accentuated by the capability to set directions dynamically, aligning with evolving content or user interactions, as demonstrated in Setting Tooltip Directions Dynamically and Tooltip Alignment.

The framework's commitment to providing a valuable tool for user guidance is highlighted in its effectiveness in clarifying the functionality of various elements, including Buttons, links, or icons. Bootstrap Tooltip not only reduces user confusion but also contributes to a cleaner interface by offering Clear explanations without clutter.