Navigation tooltips with jQuery

Navigation tooltips are a useful way to add additional information to our menus. We can create navigation tooltips by using jQuery in a simple and cross-browser manner. Let's start with a simple menu:

<ul id="navigation">
<li><a href="#">Home</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">Tutorials</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Tests</a></li>
</ul>

Then we can add some CSS styles:

#navigation {
 margin: 0;
 padding: 0;
 background: #666;
 color: #fff;
 font: bold 76% Verdana, sans-serif;
 list-style: none;
 float: left;
 width: 100%;
}

#navigation li {
 float: left;
 margin-right: 0.5em;
 height: 100%;
}

#navigation li a:link, #navigation li a:visited {
 float: left;
 display: block;
 height: 100%;
 text-decoration: none;
 padding: 0.3em;
 text-transform: uppercase;
 color: #fff;
 
}

#navigation li a:hover {
 background: #999;
}

We can also stylize our tooltip, like so:

span.tooltip {
    background: #ffc;
    border: 2px solid #999;
    color: #333;
    padding: 4px;
}

The jQuery code is very simple and is as follows:


$(document).ready(function() {
    
    
        $('#navigation li a').each(function() {
 
 var $tooltip = $('<span class="tooltip"></span>');
        var $a = $(this);
 var aText = $a.text();
 var aPos = $a.position();
 $tooltip.insertAfter($a).hide();
 
 
 switch(aText) {
 
     case 'Home':
         $tooltip.text('Home page.');
  break;
     case 'Projects':
         $tooltip.text('My projects.');
  break;
     case 'Tutorials':
         $tooltip.text('My tutorials.');
  break;
     case 'Blog':
         $tooltip.text('A blog on web standards.');
  break;
     case 'Tests':
         $tooltip.text('Tests on web standards.');
  break;
     default:
             break;

 }
 
 
 $a.mouseover(function() {
 
     $tooltip.css({
         display: 'block',
  position: 'absolute',
  top: aPos.top + 33,
                left: aPos.left,
  width: '180px',
  height: '12px'
     });
 
 });
 $a.mouseout(function() {
 
     $tooltip.hide();
 
 });
 
 
 
    
    });
    
    
    });


We basically get the coordinates of each link of our navigation menu and then we absolutely position our tooltip according to these coordinates. The tooltip we'll be showed on hover and hidden when the user moves his mouse away from a link. Note that we've inserted contextual messages depending on the text content of each link. You can see the final result here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.