Submit your widget

jQuery Animated Menu

Created 14 years ago   Views 18066   downloads 4864    Author jqueryglobe
jQuery Animated Menu
View DemoDownload
117
Share |

Step 1 – Set up the Structure

Here is the HTML markup that is used in the demo:

<div id="menu" class="menu">
 <ul>
  <li><a href="[removed];">Home</a></li>
  <li><a href="[removed];">Work</a></li>
  <li><a href="[removed];">Services</a></li>
  <li><a href="[removed];">Support</a></li>
  <li><a href="[removed];">Contacts</a></li>
 </ul>
</div>

 

The basic idea for the script is to create separated layers inside each anchor so we could animate them on hover. We will modify the DOM structure after DOM has finished loading, so each anchor will look something like this:

<a href="[removed];">
 <span class="out">Home</span>
 <span class="bg"></span>
 <span class="over">Home</span>
</a>

 

The content of anchor text will be placed inside two span elements, the third one will be used for background image.

Step 2 – Style with CSS

This is only a snippet of the CSS (for full CSS see the working example). I'm using the basic design, but you can customize it how you prefer.

.menu ul li a span {
 /* all layers will be absolute positioned */
 position: absolute;
 left: 0;
 width: 110px;
}
 
.menu ul li a span.out {
 top: 0px;
}
 
.menu ul li a span.over,
.menu ul li a span.bg {
 /* hide */  
 top: -45px;
}
 
#menu {
 background: #EEE;
}
 
#menu ul li a span {
 color: #000;
}
 
#menu ul li a span.over {
 color: #FFF;
}
 
#menu ul li span.bg {
 /* height of the menu items */  
 height: 45px;
 background: url('bg_over.gif') center center no-repeat;
}

 

Step 3 - JavaScript

I have added some inline comments so that it can be self explaining, I think.

/// wrap inner content of each anchor with first layer and append background layer
$("#menu li a").wrapInner( '<span class="out"></span>' ).append( '<span class="bg"></span>' );
 
// loop each anchor and add copy of text content
$("#menu li a").each(function() {
 $( '<span class="over">' +  $(this).text() + '</span>' ).appendTo( this );
});
 
$("#menu li a").hover(function() {
 // this function is fired when the mouse is moved over
 $(".out", this).stop().animate({'top': '45px'}, 250); // move down - hide
 $(".over", this).stop().animate({'top': '0px'},  250); // move down - show
 $(".bg", this).stop().animate({'top': '0px'},  130); // move down - show
 
}, function() {
 // this function is fired when the mouse is moved off
 $(".out", this).stop().animate({'top': '0px'},  250); // move up - show
 $(".over", this).stop().animate({'top': '-45px'}, 250); // move up - hide
 $(".bg", this).stop().animate({'top': '-45px'}, 130); // move up - hide
});