The Netlobo logo - a Nevada desert landscape

Javascript Tool-tips

Learn how to use Javascript to create tool-tips on your pages

Published May 8, 2006 by lobo235
Last updated on Jul 3, 2007

Earlier I wrote about a technique for creating tool-tips using CSS. Now, just to give you another flavor to choose from, I present Javascript tool-tips. Javascript tool-tips give you more flexibility over what your tool-tips can look like and what they can contain. Basically, anything you can throw into a div tag can be used as a tool tip including images, styles, etc.

I have tried to make this as easy as possible for you to incorporate into your own web pages. First, here is the external js file you will need to include on the page where you want the tool-tips to show up (you can download it toward the bottom of the page if you prefer):

/****************************************************************************
* JavaScript Tool-Tips by lobo235 - www.netlobo.com
*
* This script allows you to add javascript tool-tips to your pages in a very
* unobtrusive manner. To learn more about using this script please visit
* http://www.netlobo.com/javascript_tooltips.html for usage examples.
****************************************************************************/

// Empty Variables to hold the mouse position and the window size
var mousePos = null;
var winSize = null;
// Set events to catch mouse position and window size
document.onmousemove = mouseMove;
window.onresize = windowResize;
// The mouseMove and mouseCoords function track the mouse position for us
function mouseMove(ev)
{
  ev = ev || window.event;
  mousePos = mouseCoords(ev);
}
function mouseCoords(ev)
{
  if(ev.pageX || ev.pageY){
    return {x:ev.pageX, y:ev.pageY};
  }
  return {
    x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
    y:ev.clientY + document.body.scrollTop - document.body.clientTop
 };
}
// The windowResize function keeps track of the window size for us
function windowResize( )
{
  winSize = {
    x: ( document.body.clientWidth ) ?
      document.body.clientWidth : window.innerWidth ,
    y: ( document.body.clientHeight ) ?
      document.body.clientHeight : window.innerHeight
 }
}
// This function shows our tool-tips
function showTip( )
{
  var tip = document.getElementById('t'+this.id);
  tip.style.position = "absolute";
  var newTop = mousePos.y - tip.clientHeight - 10;
  var newLeft = mousePos.x - ( tip.clientWidth / 2 );
  if( newTop < 0 )
    newTop = mousePos.y + 20;
  if( newLeft < 0 )
    newLeft = 0;
  if( ( mousePos.x + ( tip.clientWidth / 2 ) ) >= winSize.x - 1 )
    newLeft = winSize.x - tip.clientWidth - 2;
  tip.style.top = newTop;
  tip.style.left = newLeft;
  tip.style.display = "block";
}
// This function moves the tool-tips when our mouse moves
function moveTip( )
{
  var tip = document.getElementById('t'+this.id);
  var newTop = mousePos.y - tip.clientHeight - 10;
  var newLeft = mousePos.x - ( tip.clientWidth / 2 );
  if( newTop < 0 )
    newTop = mousePos.y + 20;
  if( newLeft < 0 )
    newLeft = 0;
  if( ( mousePos.x + ( tip.clientWidth / 2 ) ) >= winSize.x - 1 )
    newLeft = winSize.x - tip.clientWidth - 2;
  tip.style.top = newTop;
  tip.style.left = newLeft;
}
// This function hides the tool-tips
function hideTip( )
{
  var tip = document.getElementById('t'+this.id);
  tip.style.display = "none";
}
// This function allows us to reference elements using their class attributes
document.getElementsByClassName = function(clsName){
  var retVal = new Array();
  var elements = document.getElementsByTagName("*");
  for(var i = 0;i < elements.length;i++){
    if(elements[i].className.indexOf(" ") >= 0){
      var classes = elements[i].className.split(" ");
      for(var j = 0;j < classes.length;j++){
        if(classes[j] == clsName)
          retVal.push(elements[i]);
      }
    }
    else if(elements[i].className == clsName)
    retVal.push(elements[i]);
  }
  return retVal;
}
// This is what runs when the page loads to set everything up
window.onload = function(){
  var ttips = document.getElementsByClassName('ttip');
  for( var i = 0; i < ttips.length; i++ )
  {
    ttips[i].onmouseover = showTip;
    ttips[i].onmouseout = hideTip;
    ttips[i].onmousemove = moveTip;
  }
  windowResize( );
}

There is not a whole lot to the code but I threw in a couple of comments anyway to tell what each function does. To create tool-tips you will first need to make sure you include the js_tooltips.js file in your HTML. If you have other scripts that use the window.onload event then you will run into problems unless you consolidate the two.

Next, you will need to create the hot-spots for your tool-tips that can be hovered over by the user. To do this, simply create some <span> elements with the class name 'ttip' and an id as seen below:

<span class="ttip" id="def">Hot-spot</span>

You can style these span tags however you wish but I recommend styling them similar to the hot-spots in the example because that it what most users are used to.

Now, you need to create some <div> tags that contain the actual tool-tip. The divs must have the same id as the span tag they belong to but with a letter 't' in front of the id. For example, the div tag containing the tool-tip for the above span tag would look like this:

<div class="moreinfo" id="tdef">This is the tooltip</div>

If you do not assign the ids correctly to your spans and divs they will not be linked to eachother properly. You should style the tool-tip div so that it has a background color so that it does not appear transparent when it comes up even if the color is white. You also should make sure that the div is styled to have 'display: none' so that it does not appear anywhere on your page but instead is hidden.

The script is semi-smart in that it will try not to pop up a tool-tip off of the browser window. Also, I know for sure that this script is compatible with the latest versions of IE, Firefox, Opera, and Konquerer. Your mileage may vary depending on the browser but please let us know if you have any problems with a specific browser especially if you know of a fix to make it compatible.

Here is an example page where you can see the Javascript tool-tips in action: Example

Here is a link to the Javascript tool-tips code: js_tooltips.js

4 comments for this article.

del.icio.us logo add this article to del.icio.us!
Other great Web Development and Programming articles on Netlobo.com:
Resizing an Image Using PHP and the GD2 Library
CSS Tool-tips
Clean URLs using Apache's mod_rewrite