Add a tooltip to a button

Description: Add a tooltip “Save the file” to a button, which opens when the user hovers on it.

Hint:

  • Use data-bs-toggle="tooltip", data-bs-title and start it with new bootstrap.Tooltip().

Solution

<button type="button" class="btn btn-success" id="savebtn" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Save the file">Save</button>
<script>
  document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(function (el) { new bootstrap.Tooltip(el); });
</script>
Live preview

const b = document.getElementById('savebtn');
b.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
await new Promise(r => setTimeout(r, 400));
const t = document.querySelector('.tooltip');
console.log('tooltip shown: ' + (t !== null) + ', text: ' + (t ? t.textContent.trim() : ''));
Console output (real Chrome)

tooltip shown: true, text: Save the file

How it works

  • Tooltips are not started automatically. The small script finds all elements with data-bs-toggle="tooltip" and starts them.

Read Tooltips and Popovers.


Learn more about the similar topics:
Tutorials
Bootstrap Modal
Bootstrap Collapse and Accordion
Bootstrap Carousel
Bootstrap Tooltips and Popovers
Bootstrap Offcanvas
Bootstrap Toasts
Bootstrap JavaScript: Data Attributes, API and Events
Exercises & Assignments
Open a modal with a button
Create an accordion with three items
Create a carousel with three slides
Add a tooltip to a button
Create an offcanvas sidebar which opens from the left
Interview Questions & Answers
How do you open a modal in Bootstrap?
How do you create a carousel in Bootstrap?
What are data-bs-* attributes in Bootstrap?
How do you initialize tooltips and popovers in Bootstrap 5?
What is the offcanvas component in Bootstrap?
What is Popper and why does Bootstrap need it?
How do you use the Bootstrap JavaScript API?