jQuery: sliding menu items

jQuery can actually add some interesting visual effects to our menus with a minimum effort. In this post I'll show you how to create the effect of sliding menu items on a simple navigation menu. Our menu will have only the first item visible by default. When a user moves the mouse over an item, the next one will be shown with a sliding movement. And so on. To start with, let's take a look at our basic markup structure which basically consists of a plain unordered list:

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

In our CSS we need only to declare each list item as relatively and set its overflow property to hidden. This is due to the fact that the width of each item will be zeroed by jQuery and its left property's value will be changed to a negative value which corresponds to the overall width the aforementioned item:

#navigation {
 width: 40%;
 margin: 0 auto;
 padding: 0;
 height: 2em;
 list-style: none;
 border-bottom: 2px solid #333;
}

#navigation li {
 float: left;
 height: 2em;
 margin-right: 0.5em;
 position: relative;
 overflow: hidden;
}

#navigation a {
 float: left;
 height: 2em;
 padding: 0 1em;
 line-height: 2;
 font-weight: bold;
 background: #333;
 color: #fff;
 text-decoration: none;
 border-radius: 6px 6px 0 0;
}

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

Now with jQuery we have only to make the items slide when a user hovers the menu links. Before doing so, we also need to zero the width of the list items (except the first one) and add a negative left offset to them to create the entry effect:

$(function() {
$('li', '#navigation').not(':first').each(function() {

  var $li = $(this);
  $li.css('width', 0);
  
  $li.css('left', - $li.width());


});

$('li', '#navigation').each(function() {


  var $li = $(this);
  var next = $li.next();
  var $a = $('a', $li);
  
  $a.mouseover(function() {
  
    if(next.width() == 0) {
    
      next.animate({
        width: 100,
        left: 0
      }, 1000);
    
    
    }
  
  
  
  });
  


});

});

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.