jQuery: advanced tooltip menu

In this post I'm going to show you how to create advanced tooltip menus with jQuery and a couple of CSS rules. To accomplish this, we need a solid markup structure to work with. Basically, for optimum performance we need that our tooltips must already be present in the markup, as shown below:

<ul id="navigation">

 <li><a href="#" class="t1">Home</a></li>
 <li><a href="#" class="t2">About</a></li>
 <li><a href="#" class="t3">Contacts</a></li>

</ul>

<div class="tooltip" id="t1">
 <span>Our home page</span>
</div>

<div class="tooltip" id="t2">

 <span>About us</span>

</div>

<div class="tooltip" id="t3">

  <span>Contact us</span>

</div>

Every link in the navigation menu is internally connected to its corresponding tooltip thanks to the class and ID selectors specified on these elements. In turn, our CSS styles are really simple:

#navigation {
 height: 6em;
 font: 100% Arial, sans-serif;
 margin: 0;
 padding: 0 1em;
 list-style: none;
 background: #000 url(menu-bg.png) repeat-x;
}

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

#navigation a {
 float: left;
 display: block;
 color: #fff;
 height: 100%;
 line-height: 6;
 padding: 0 1em;
 text-decoration: none;
 font-weight: bold;
 text-transform: uppercase;
}

#navigation a:hover {
 background: url(menu-bg-hover.png) repeat-x;
}

div.tooltip {
 width: 151px;
 height: 80px;
 text-align: center;
 color: #fff;
 font: small Arial, sans-serif;
 background: url(menu-tooltip.png) no-repeat;
 position: absolute;
 display: none;
}

div.tooltip span {
 display: block;
 width: 100%;
 height: 100%;
 line-height: 90px;
}

Our tooltips have been absolutely positioned and hidden. This will be clear in a moment:

$(document).ready(function() {

  $('#navigation li').each(function() {
  
    var $li = $(this);
    var $a = $li.find('a');
    var id = '#' + $a.attr('class');
    
    $a.mouseover(function() {
    
      var top = 100;
      var left = $a.offset().left;
      
      $(id).css({top: top, left: left}).fadeIn(1000);
    
    
    
    });
    
    $a.mouseleave(function() {
    
      $(id).fadeOut(1000);
    
    
    });
  
  
  });

});

We've used the class attribute of each link to select the corresponding tooltip element. Our tooltips have been first positioned using the css() method and then shown using fadeIn(). You can see the demo below.

Demo

Live demo

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.