JavaScript: How to Create Tooltip

, , …,
Want to master JavaScript in a week? Buy Xah JavaScript Tutorial.

This page shows you how to do floating balloon (aka tooltip) using JavaScript, without using any JavaScript library.

Hover over me to see a example.

Here's the HTML code:

<p><span id="t42310">Hover over me</span></p>

Here's the JavaScript code:

// -*- coding: utf-8 -*-
// © 2013 Xah Lee,
// if you use, please give credit and link. Thanks.

function createTooltipElement () {
    // create balloon element to display info
    bubbleBox = document.createElement("div");

    // set style"hidden"; // ← CRITICAL trick: make it hidden till mouse over"fixed";"1ex";"1ex";"30px";"silver";

    // insert into DOM
    bubbleBox.appendChild(document.createTextNode("i'm nothing"));
    document.body.insertBefore(bubbleBox, document.body.firstChild);

function assignHandler () {
    var hoverEle = document.getElementById("t42310");
    // assign handler
    hoverEle.addEventListener("mouseover", bubbleActivate , false);
    hoverEle.addEventListener("mouseout", bubbleDeactivate , false);

function bubbleActivate (evt) {

    // get the position of the hover element
    var boundBox =;
    var coordX = boundBox.left;
    var coordY =;

    // adjust bubble position  (coordX + 40).toString() + "px"; (coordY + 40).toString() + "px";

    // add bubble content. Can be any HTML
    bubbleBox.innerHTML = "<span style='font-size:12ex;color:red'>" + "♥" + "</span>";

    // make bubble VISIBLE"visible";

function bubbleDeactivate(evt) {"hidden";

// ------------------------------
// initialization

// the tooltip element.
var bubbleBox;

// create the element

// assign mouse over event to handler

Here's how it works:

  1. Use JavaScript to create a HTML element. This will be your tooltip box.
  2. Make the tooltip box invisible, by setting CSS visibility:hidden.
  3. Set the tooltip box on its own layer (CSS position:fixed), so that it doesn't interfere with other elements on the page.
  4. Assign function/handler to the “mouse over” and “mouse out” events, for elements that you want tooltip box to appear.
  5. The function to activate the tooltip, will change tooltip's CSS so it's visible (visibility:visible), and also position it near the mouse. Also add whatever content you want to the tooltip.
  6. The function to deactivate the bubble, will change the tooltip's CSS so it's invisible again.

If you have trouble understanding the code, here's some detail on how to do each step:

That's it!

For a more complex example of bubble box, see: Unicode: Stars, Crosses, Dingbats ★ ♥ ✜ ☪ ☯ ☺ ☠.

blog comments powered by Disqus