Pure CSS Tooltip and JavaScript Implementation


CSS Only Tooltip

See demo first. Move the cursor (mouse pointer) to hover over the blue text with underline:

This is a tooltip example.

I modified the example of MDN [1] and make it simpler. The source code is as follows:

HTML:

This is a <span data-descr="hello, I am tooltip!">tooltip</span> example.

The texts in data-descr attribute of the span element is the texts to be displayed in the tooltip when the cursor hovers over the span element.

CSS:

span[data-descr] {
    position: relative;
    text-decoration: underline;
    color: blue;
    cursor: help;
}
span[data-descr]:hover::after {
    content: attr(data-descr);
    position: absolute;
    left: 0;
    top: 1.25em;
    background-color: yellow;
    border: 1px gray solid;
    border-radius: 3px;
    padding: 3px;
}

The tooltip is in fact an ::after pseudo-element, and attr() CSS expression is used to retrieve the value of an data-descr attribute of the span element, and put the value in the content of the pseudo-element.

JavaScript Implementation

See demo first. Move the cursor (mouse pointer) to hover over the blue text with underline:

This is a tooltip example via JavaScript.

This demo is almost the same as the CSS demo, except that it is implemented by JavaScript. The following is complete source code.

HTML: one more div element is inserted and invisible in the beginning. This div wiil be used as the tooltip.

<div class="tooltip invisible"></div>
This is a <span data-text="hello, I am tooltip!">tooltip</span> example via JavaScript.

CSS:

span[data-text] {
    text-decoration: underline;
    color: blue;
    cursor: help;
}
.invisible {
    display: none;
}
.tooltip {
    position: absolute;
    background-color: yellow;
    border: 1px gray solid;
    border-radius: 3px;
    padding: 3px;
}

JavaScript: Use querySelectorAll to find all span elements with data-text attibute, and setup corresponding mouseenter/mouseleave event handlder to show/hide the tooltip.

var tooltip = document.querySelector(".tooltip");

function ShowTooltip(e) {
  var elm = e.target;
  tooltip.style.left = elm.offsetLeft + 'px';
  tooltip.style.top = (elm.offsetTop + elm.offsetHeight + 5) + 'px';
  tooltip.textContent = elm.dataset.text;
  tooltip.classList.remove("invisible");
}

function HideTooltip(e) {
  tooltip.classList.add("invisible");
}

var spans = document.querySelectorAll("span[data-text]");
for (var i = 0; i < spans.length; ++i) {
  var span = spans[i];
  span.addEventListener("mouseenter", ShowTooltip);
  span.addEventListener("mouseleave", HideTooltip);
}

Summary

If only simple texts are in the tooltip, use CSS only solution. If you need to retrieve the content of tooltip via XHR and perform complicated tasks, choose JavaScript implementation.

Tested on: Chromium Version 56.0.2924.76 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)