jQuery: expanding menu items animation

Expanding menu items with jQuery is pretty straightforward. Thanks to the animate() method we can add some nice effects when a user hovers a link with his/her mouse. We can start from a simple navigation menu like this:

<ul id="navigation">
    <li><a href="#">Home</a></li>
    <li><a href="#">About Us</a></li>
    <li><a href="#">Contacts</a></li>
</ul>

Then we attach some styles to it:

#navigation {
 width: 10em;
 list-style: none;
 margin: 0;
 padding: 0;
 color: #333;
}

#navigation li {
 height: 100%;
 margin-bottom: 0.5em;
 line-height: 1.4;
 padding-bottom: 2px;
 border-bottom: 1px solid #999;
}

#navigation a {
 color: #338;
 font-weight: bold;
 text-decoration: none;
 border-left: 10px solid #fff;
}

#navigation a:hover {
 border-left-color: #999;
 background: #eee;
}

Finally, we can use jQuery:

$(document).ready(function() {


    $('#navigation li a').each(function() {
    
        var $a = $(this);
 var baseFontSize = $a.css('fontSize');
 
 $a.hover(function() {
 
     $a.animate({
        display: 'block',
        textAlign: 'center',
        fontSize: '1.5em'}, 'slow');
 
 }, function() {
 
     $a.animate({
         display: 'inline',
  fontSize: baseFontSize}, 'slow');
  
  
  
 });
    
    
    });


});

In this case we change only some CSS properties for each link and we restore them when we've finished, that is, when the user moves his/her mouse away from the link. Note that this code doesn't work in IE 6, 7 and 8. 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.