jQuery: accessible tooltip menu

Screen readers usually interpret the declarations display: none and visibility: hidden, even though they're part of a visual style sheet. The result is that they're not able to read aloud the content of an element having these declarations attached to it. Many jQuery menus that make use of such declarations are not fully accessible because some elements remain hidden. In this post I'm going to show you how to create a tooltip menu whose contents are fully accessible.

Our markup first:

<ul id="navigation">

 <li><a href="#">Home</a><span class="tip">This site</span></li>
 <li><a href="#">About</a><span class="tip">About us</span></li>
 <li><a href="#">Contacts</a><span class="tip">Contact us</span></li>

</ul>

The elements with class tip will be first hidden using negative absolute positioning and then revealed when a user moves his mouse over a link. This class has the following background image that will draw the tooltip balloon:

Here are our CSS styles:

#navigation {
 width: 50%;
 margin: 0 auto;
 padding: 0 1em;
 height: 2em;
 background: #333;
 list-style: none;
 color: #fff;
 font: 100% Arial, sans-serif;
 border-top: 5px solid #999;
 border-bottom: 5px solid #999;
}

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

#navigation a {
 float: left;
 width: 100%;
 height: 100%;
 line-height: 2;
 font-weight: bold;
 text-align: center;
 color: #fff;
 text-decoration: none;
}

#navigation a:hover {
 background: #666;
}

#navigation li span.tip {
 width: 159px;
 height: 62px;
 line-height: 62px;
 display: block;
 text-align: center;
 background: url(tooltip.png) no-repeat;
 position: absolute;
 top: -1000em;
}

Since we're using absolute positioning, we first need to calculate the top offset of each link, subtract a certain length and then use the returned length to position our tooltip on hover:

$('#navigation a').each(function() {
  
    var $a = $(this);
    var offsetTop = $a.offset().top;
    
    $a.mouseover(function() {
    
      $a.next().animate({
        top: offsetTop - 80
      }, 500);
    
    
    });
    
    $a.mouseleave(function() {
    
    
      $a.next().animate({
        top: '-1000em'
      }, 500);
    
    
    });
  
  
  
});

As you can see, we use the default value of -1000em to make the tooltip disappear when a user leaves the link region. 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.