ToolTip on Hover in JavaScript

  1. JavaScript ToolTip
  2. ToolTip on Mouse Hover Using HTML and JavaScript
ToolTip on Hover in JavaScript

This article will discuss creating ToolTip and displaying it on mouse hover using HTML and JavaScript.

JavaScript ToolTip

In HTML and JavaScript, we can create a small box and toggle its visibility as a ToolTip. We deal with enabling or disabling the visibility of the ToolTip by using a JavaScript custom function.

ToolTip on Mouse Hover Using HTML and JavaScript

The hover event triggers when we place the mouse cursor without a click on any component of a webpage.

In JavaScript, we can call and toggle the tooltip box on mouse hover whenever the user places the cursor on an item, and we can display the tooltip as a pop-up message.

We can create a tooltip feature using HTML and CSS. Creating a tooltip and displaying some text about the item will save our initial space on the web page.

Example Code:

<!DOCTYPE html>
<html>
   <head>
      <style>
         body {
         text-align: center;
         }
         .class {
         -webkit-user-select: none;
         position: relative;
         }
         .displayText {
         position: absolute;
         bottom: -230%;
         left: 50%;
         margin-left: -80px;
         width: 160px;
         background-color: lightgrey;
         text-align: center;
         border-radius: 6px;
         padding: 8px 0;
         visibility: hidden;
         }
         .displayText::before {
         content: "";
         border-width: 5px;
         border-style: solid;
         top: -28%;
         left: 35%;
         border-color: transparent transparent lightgrey transparent;
         position: absolute;
         }
         .show {
         visibility: visible;
         }
      </style>
   </head>
   <body>
      <h2>DelftStack learning</h2>
      <h3>JavaScript open tooltip on hover</h3>
      <div class="class" onmouseover="openToolTip()">Hover on me to open ToolTip
         <span class="displayText" id="displayText">ToolTip Text</span> <! –– tooltip box and text ––>
      </div>
      <script>
         function openToolTip () {
         var tooltipPopup = document.getElementById("displayText");
         tooltipPopup.classList.toggle("show"); // toggle the tooltip
         }
      </script>
   </body>
</html>

Output:

tooltip on mouse hover javascript

In above html source, we used div tag <div></div> which make a box in webpage. The <div> tag is defining the class and using onmouseover function to call the openToolTip() function.

Inside the <div>, we used the <span> element as our tooltip text and defined the id. In <script> tags we declared openToolTip() function in which we will call toggle method and passed "show".

Here, the CSS deals with the visibility of the tooltip, and we used CSS properties for basic styling and positioning for the tooltip.