Display tooltip to div with pure css and javascript in html example


Tooltip in HTML is important information to be displayed in a element while mouse overs an elements. A element can be div, button,input controls.

This tutorials explains adding tooltip to div element with examples

There are multiple ways we can add tooltip to Div element in html pages

  • Pure css
  • Pure Javascript

How to add tooltip to div element with pure CSS

<div class="tooltipContainer"> Name
    <span class="tooltip">Please enter name</span>
  <input type="text" name="name"/>
</div>

CSS code:

.tooltipContainer {
  position: absolute;
  display: inline-block;
  cursor: pointer;
}

.tooltipContainer .tooltip {
  visibility: hidden;
  width: 130px;
  background-color: blue;
  color: #fff;
  text-align: left;
  border-radius: 6px;
  padding: 5px 10px;
  position: absolute;
  z-index: 1;
  bottom: 160%;
  left: 100%;
  margin-left: -140px;
  opacity: 0;
  transition: opacity 1s;
}

.tooltipContainer .tooltip::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -15px;
  border-width: 15px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

.tooltipContainer:hover .tooltip {
  visibility: visible;
  opacity: 1;
}

In the above example, No javascript is added

Display Tooltip with pure javascript

In this example, Html mouse events like onmouseover and onmouseout are being used for tool tip display.

onmouseover event is called when element get focus with mouse.

onmouseout event is called when element lost focus.

create a tooltip text with custom styles, this will not be shown by default. When mouse hovers it, tooltip is shown using element.display.style=block else display=none as shown below

Codepen tooltip pure css and javascript example You can check complete example code for adding tooltip with pure css and javascript

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.