This page shows you how to do floating balloon (aka tooltip) using JavaScript, without using any JavaScript library or framework.
Hover over me to see a example.
Here's the HTML code:
<p><span id="t42310">Hover over me</span> to see a example.</p>
Here's the JavaScript code:
// -*- coding: utf-8 -*- // © 2013 Xah Lee, http://xahlee.info/ // if you use, please give credit and link. Thanks. function createBubbleElement () { // create balloon element to display info bubbleBox = document.createElement("div"); bubbleBox.appendChild(document.createTextNode("i'm nothing")); // set style bubbleBox.style.visibility="hidden"; // ← CRITICAL trick: make it hidden till mouse over bubbleBox.style.position="fixed"; bubbleBox.style.top="1ex"; bubbleBox.style.left="1ex"; bubbleBox.style.borderRadius="30px"; bubbleBox.style.backgroundColor="silver"; // insert into DOM 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 = evt.target.getBoundingClientRect(); var coordX = boundBox.left; var coordY = boundBox.top; // adjust bubble position bubbleBox.style.left= (coordX + 40).toString() + "px"; bubbleBox.style.top= (coordY + 40).toString() + "px"; // add bubble content. Can be any HTML bubbleBox.innerHTML = "<span style='font-size:12ex;color:red'>" + "♥" + "</span>"; // make bubble VISIBLE bubbleBox.style.visibility="visible"; } function bubbleDeactivate(evt) { bubbleBox.style.visibility="hidden"; } // ------------------------------ // initialization // the bubble element. // this must be global, because other functions will need to control it var bubbleBox; // create the element createBubbleElement(); // assign handler (function) to mouse over event assignHandler();
The code is pretty simple.
The trick of popup balloon is basically this:
visibility:hiddenposition:fixed), so that it doesn't interfere with other elements on the page.visibility:visible), and also position it near the mouse. Also add whatever content you want to the Bubble Box.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: Dingbats, Cultural Symbols.
blog comments powered by Disqus