Introduction
Tooltip is a graphical user interface component. When we hover on a UI element, we get some information in a popover about that UI element that is known as a tooltip of the UI element.
Why we use a tooltip
To display some information about an element or hint or help.
Example
If we have a table with column names - ListItem and UserInterface. To save some real estate on the UI, we can use LI and UI as their labels but to display details, we can have tooltips on the hover. We can also use Tooltips to display more details about the action of an element.
How to create a tooltip in Bootstrap
To create a tooltip add bootstrap libraries to your code.
Add the data-toggle="tooltip" atribute to an element.
Add your description in the title atribute.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <title>Tooltip Example</title>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
- </head>
- <body>
-
- <div class="container">
- <table class="table table-striped">
- <thead>
- <tr>
- <th>Sl.No</th>
- <th>Car Name</th>
- <tr>
- </thead>
- <tbody id="tblCarLists"><tbody>
- </table>
-
- </div>
-
- <script>
- $(document).ready(function(){
- var car=["Bmw","Maruti","Jaguar"]
- for(i=0;i<car.length;i++){
- var html="<tr><td data-toggle='tooltip' title="+Number(1+i)+">"+Number(1+i)+"</td><td data-toggle='tooltip' title="+car[i]+">"+car[i]+"</td></tr>";
- $("#tblCarLists").append(html);
- }
-
- $('[data-toggle="tooltip"]').tooltip();
- });
- </script>
-
- </body>
- </html>
In the above code, I've used tooltip in a <td> element. When an user will hover on a <td> element, user will get the information about that <td> on a popup.
How to change a tooltip position
By default, tooltip appears on the top of the element. To change the tooltip position we use data-placement attribute.
Example:
- <td data-toggle='tooltip data-placement="top"' title="+Number(1+i)+">"+Number(1+i)+"</td>
- <td data-toggle='tooltip' data-placement="bottom" title="+Number(1+i)+">"+Number(1+i)+"</td>
- <td data-toggle='tooltip' data-placement="left" title="+Number(1+i)+">"+Number(1+i)+"</td>
- <td data-toggle='tooltip' data-placement="right" title="+Number(1+i)+">"+Number(1+i)+"</td>
Summary
In this blog, we discussed how to create a tooltip using jQuery .