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-titleand start it withnew 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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |