JS DOM: Create Tooltip
Tooltip Example
This page shows you how to do floating tooltip, without using any JavaScript library.
Hover over me to see tooltip.
Code
<span id="hotbox846">Hover over me</span>
"use strict"; // create a tooltip // © 2013, 2025 Xah Lee, http://xahlee.info/ // created 2013 // version 2025-04-23 { const hotbox846 = document.getElementById("hotbox846"); // create tooltip element const tipbox = document.createElement("div"); // set style tipbox.id = "tip962"; tipbox.style.visibility = "hidden"; // make it hidden till mouse over tipbox.style.position = "fixed"; tipbox.style.top = "8px"; tipbox.style.left = "8px"; tipbox.style.padding = "8px"; tipbox.style.width = "300px"; tipbox.style.borderRadius = "16px"; tipbox.style.border = "solid thin grey"; tipbox.style.color = "black"; tipbox.style.backgroundColor = "bisque"; // insert into DOM document.body.appendChild(tipbox); const f_TurnOn = ((evt) => { // get the position of the hover element const boundBox = evt.target.getBoundingClientRect(); const coordX = boundBox.left; const coordY = boundBox.top; // adjust bubble position tipbox.style.left = (coordX + 40).toString() + "px"; tipbox.style.top = (coordY + 40).toString() + "px"; // add bubble content. Can include image or link tipbox.innerHTML = "some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing some thing."; // make bubble VISIBLE tipbox.style.visibility = "visible"; }); const f_TurnOff = (() => { tipbox.style.visibility = "hidden"; }); hotbox846.addEventListener("mouseover", f_TurnOn, false); hotbox846.addEventListener("mouseout", f_TurnOff, false); document.getElementById("tip962").addEventListener("click", f_TurnOff, false); }
How it Works
- Use JavaScript to create a HTML element. This will be your tooltip box.
- Make the tooltip box invisible, by setting CSS
visibility:hidden
. - Set the tooltip box on its own layer (CSS
position:fixed
), so that it doesn't interfere with other elements on the page. - Assign function/handler to the “mouse over” and “mouse out” events, for elements that you want tooltip box to appear.
- 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. - The function to deactivate the bubble, will change the tooltip's CSS so it's invisible again.
- JS DOM: Create and Insert HTML Element
- CSS: Position Fixed
- CSS: Hide Element (visibility)
- JS DOM: Change CSS
- JS DOM: Change Element Content
That's it!