Bootstrap Tooltips

Creating the Tooltips with Bootstrap

A tooltip is a small pop up that appears when user places the mouse pointer over an element such as link or buttons to provide hint or information about the element being hovered.

Tooltips can be very helpful for the new visitors of your website because they enable the user to know the purpose of icons and links by placing the mouse pointer over them.

Step 1: Adding the Tooltip Markup

To create a tooltip, you need to add the data-bs-toggle="tooltip" attribute to an element. Tolltip text that would display on hover can be specified using the title attribute.

Here is the standard markup for adding a tolltip to a hyperlink.

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

Similarly, you can add tooltips to the other elements such as buttons, icons, etc.

Step 2: Enabling the Tooltips

Tooltips can be enabled via JavaScript — just call the tooltip() Bootstrap method with the idclass or any CSS selector of the target element in your JavaScript code.

You can either initialize tooltips individually or all in one go. The following jQuery code will initialize all tooltips on the page by selecting them by their data-bs-toggle attribute.

Example

jQuery JavaScript

Try this code »

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

— The output of the above example will look something like this:

Bootstrap Tooltip

Note: For performance reasons the tooltip data-apis are opt in, means to use tooltips you must initialize them yourself. Also, tooltips with zero-length titles are never displayed, as well as triggering tooltips on hidden elements will not work.

Tip: Tooltips for .disabled or disabled elements must be triggered on a wrapper element. Also, when tooltips are triggered from hyperlinks that span multiple lines, it will be centered. You can use white-space: nowrap; on those hyperlinks to avoid this behavior.


Setting the Directions of Tooltips

You can set tooltips to appear on top, right, bottom and left sides of an element.

Positioning of Tooltips via Data Attributes

The following example will show you how to set the direction of tooltips via data attributes.

Example

Try this code »

<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 following example will show you how to set the direction of tooltips via JavaScript.

Example

jQuery JavaScript

Try this code »

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

Options

There are certain options which may be passed to tooltip() Bootstrap method to customize the functionality of the tooltip plugin.

NameTypeDefault ValueDescription
animationbooleantrueApply a CSS fade transition to the tooltip.
containerstring | element | falsefalseAppends the tooltip to a specific element.Specify container: 'body' to avoid rendering problems in more complex components (like input groups, button groups, etc.)
delaynumber | object0Time to delay in showing and hiding the tooltip (ms) — does not apply to manual trigger type.If a number is supplied, delay is applied to both hide/showObject structure is: delay: { "show": 500, "hide": 100 }
htmlbooleanfalseInsert HTML into the tooltip.If true, HTML tags in the tooltip’s title will be rendered in the tooltip. If false, innerText property will be used to insert content into the DOM.Use simple text if you’re worried about XSS attacks.
placementstring | function‘top’Sets the position of the tooltip — auto | top | bottom | left | right.When auto value is specified, it will dynamically reorient the tooltip.
selectorstring | falsefalseIf a selector is provided, tooltip objects will be attached to the specified targets.This is normally used to apply tooltips to dynamically added DOM elements.
templatestring'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'Base HTML to use when creating the tooltip.The tooltip’s title will be inserted into the .tooltip-inner element.The .tooltip-arrow element will become the tooltip’s arrow.The outermost wrapper element should have the .tooltip class.
titlestring | element | functionSets the default title value if title attribute isn’t present.
triggerstring‘hover focus’Specify how tooltip is triggered — click | hover | focus | manual. You can pass multiple triggers; separated with a space.The value manual indicates that the tooltip will be triggered programmatically via the .show().hide() and .toggle() methods; this value cannot be combined with any other trigger.
fallbackPlacementsarray[‘top’, ‘right’, ‘bottom’, ‘left’]Allows you to specify which placement Popper will use on fallback.
boundarystring | element‘clippingParents’Overflow constraint boundary of the tooltip (applies only to Popper’s preventOverflow modifier). It can also accept an HTMLElement reference (via JavaScript only).
customClassstring | functionAdd classes to the tooltip when it is shown. Please note that these classes will be added in addition to any classes specified in the template. To add multiple classes, separate them with spaces like: 'class1 class2'.You can also pass a function that should return a single string containing additional class names.
sanitizebooleantrueEnable or disable the sanitization. If activated 'template' and 'title' options will be sanitized.
allowListobjectDefault valueObject which contains allowed attributes and tags.
sanitizeFnnull | functionnullAllows you to specify your own sanitize function.
offsetarray | string | function[0, 0]Offset of the tooltip relative to its target. You can also pass a string in data attributes with comma separated values like: data-bs-offset="10,20"
popperConfignull | object | functionnullAllows you to change Bootstrap’s default Popper config, see Popper’s configuration.

You can set these options either through the use of data attributes or JavaScript. For setting the tooltips options via data attributes, just append the option name to data-bs- along with the correct value, like data-bs-animation="false"data-bs-placement="bottom" etc.

Also, when passing the options via data attributes make sure to change the case type of the option name from camelCase to kebab-case. For example, instead of using data-bs-customClass="my-class", use data-bs-custom-class="my-class".

However, JavaScript is the preferred way of setting these options as it prevents you from repetitive work. See the passing options section below to know how to set the options for tooltips via JavaScript.


Methods

These are the standard Bootstrap’s tooltip methods:

Passing options

You can additionally pass options to the tooltips using options object.

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

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#myTooltip").tooltip({
        title : "It looks like title attribute is not present."
    });
});
</script>

The following example will show you how to place the HTML content inside a tooltip:

Example

jQuery JavaScript

Try this code »

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

The following example will show you how to control the timing of showing and hiding the tooltip using the tooltip’s delay option dynamically via JavaScript.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    // Show and hide tooltip with same speed
    $("#tinyTooltip").tooltip({
        delay: 100
    });
    
    // Show and hide tooltip with different speed
    $("#largeTooltip").tooltip({
        delay: {show: 0, hide: 2000}
    }); 
});
</script>

The following example will show you how to create your own custom template for Bootstrap tooltips instead of using the default one dynamically via JavaScript.

Example

jQuery JavaScript

Try this code »

<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>

The following example will insert the dynamically generated HTML code of the tooltip at the end of the #wrapper element instead of the default <body> element.

Example

jQuery JavaScript

Try this code »

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

Note: Overriding the tooltip’s default container option value does not produce any visible difference on page. To see the actual result you need to inspect the DOM. Press Ctrl+Shift+I (Windows / Linux) or Cmd+Opt+I (Mac) to open Developer tools or DOM Inspector.

Similarly, you can set other options for the tooltips. Let’s check out the other methods of the Bootstrap tooltip plugin.

show

This method reveals an element’s tooltip. This is considered a “manual” triggering of the tooltip.

Example

jQuery JavaScript

Try this code »

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

hide

This method hides an element’s tooltip. This is considered a “manual” triggering of the tooltip.

Example

jQuery JavaScript

Try this code »

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

toggle

This method toggles an element’s tooltip. This is considered a “manual” triggering of the tooltip.

Example

jQuery JavaScript

Try this code »

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

dispose

This method hides and destroys an element’s tooltip (i.e. removes stored data on the DOM element).

Example

jQuery JavaScript

Try this code »

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

enable

This method gives an element’s tooltip the ability to be shown. Tooltips are enabled by default.

Example

jQuery JavaScript

Try this code »

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

disable

This method removes the ability for an element’s tooltip to be shown. The tooltip will only be able to be shown if it is re-enabled.

Example

jQuery JavaScript

Try this code »

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

toggleEnabled

This method toggles the ability for an element’s tooltip to be shown or hidden.

Example

jQuery JavaScript

Try this code »

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

update

This method updates the position of an element’s tooltip.

Example

jQuery JavaScript

Try this code »

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

getInstance

This is a static method which allows you to get the tooltip instance associated with a DOM element.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    // Trigger the tooltip
    $("#myTooltip").tooltip();
    
    // Get tooltip instance on button click
    $("#myBtn").click(function(){      	
        var myTooltip = bootstrap.Tooltip.getInstance($("#myTooltip")[0]);
        console.log(myTooltip);
        // {_element: a#myTooltip, _isEnabled: true, _timeout: 0, _hoverState: "", _activeTrigger: {…}, …}
    });
});
</script>

getOrCreateInstance

This is a static method which allows you to get the tooltip instance associated with a DOM element, or create a new one in case if the tooltip wasn’t initialized.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    // Get or create tooltip instance on button click
    $("#myBtn").click(function(){
        var myTooltip = bootstrap.Tooltip.getOrCreateInstance($("#myTooltip")[0]);
        console.log(myTooltip);
        // {_element: a#myTooltip, _isEnabled: true, _timeout: 0, _hoverState: "", _activeTrigger: {…}, …}
    });
});
</script>

Events

Bootstrap’s tooltip class includes few events for hooking into tooltip functionality.

EventDescription
show.bs.tooltipThis event fires immediately when the show instance method is called.
shown.bs.tooltipThis event is fired when the tooltip has been made visible to the user. It will wait until the CSS transition process has been fully completed before getting fired.
hide.bs.tooltipThis event is fired immediately when the hide instance method has been called.
hidden.bs.tooltipThis event is fired when the tooltip has finished being hidden from the user. It will wait until the CSS transition process has been fully completed before getting fired.
inserted.bs.tooltipThis event is fired after the show.bs.tooltip event when the tooltip template has been added to the DOM.

The following example will display an alert message to the user when the fade out transition of the tooltip has been fully completed.

Example

jQuery JavaScript

Try this code »

<script>
$(document).ready(function(){
    $("#myTooltip").on("hidden.bs.tooltip", function(){
        alert("Tooltip has been completely closed.");
    });
});
</script>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *