stackemedia

Create a JavaScript tooltip

This was posted in JavaScript on June 17th, 2009

Use the following code to create a JavaScript tooltip. Click here to view an example.

First add html to your page to create the popup:

<div id=”FloatBox” class=”hideFloatBox”>Hello World!</div>

Then add the following CSS to your style sheet (between the < head> tags (or you could use a CSS style sheet):

<style type=”text/css”>
.hideFloatBox
{
display: none;
}

.displayFloatBox
{
position: fixed;
_position: absolute;
z-index:200;
}

#FloatBox
{
padding: 5px;
width: 200px;
height: 20px;
border: solid 1px #cecece;
background-color: #ffffff;
}
</style>

Now add your JavaScript to the page (also between the <head> tags:

<script language=”javascript” type=”text/javascript”>
var floatBox;
var boxVisible = false;
var nav = (navigator.appName == “Netscape”);
var Xoffset = -5;
var mouseX;
var mouseY;

if(nav)document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = getMouse;

///< summary>
/// Gets the mouse position on screen.
///< /summary>
function getMouse(e)
{

mouseX = (nav) ?e.pageX : event.x;
mouseY = (nav) ?e.pageY : event.y;

if(boxVisible)
{
moveFloatBox(mouseX, mouseY);
}
}

///<summary>
/// Moves the floating box.
///</summary>
function moveFloatBox(x, y)
{
floatBox.style.left = (x + Xoffset) + “px”;
floatBox.style.top = (document.body.scrollTop + y + 20) + “px”;
}

///< summary>
/// Displays the floating box.
///< /summary>
function showFloatBox()
{
floatBox = document.getElementById(“FloatBox”);
floatBox.className = “displayFloatBox”;
boxVisible = true ;
}

///< summary>
/// Hides the floating box.
///< /summary>
function hideFloatBox()
{
floatBox.className = “hideFloatBox”;
}

</script>


Tested browsers: firefox, chrome, IE8