To build a jQuery menu with cursor we only need to insert an hidden element in our main menu container. When a user hovers a link, our cursor will be positioned just under the current item while getting the width and the position of that item. We're going to use the animate()
method together with the mouseover
event. Let's see how it works.
First of all, the markup:
<div id="navigation"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contatti</a></li> </ul> <div id="cursor"></div> </div>
The cursor element can actually be inserted via jQuery. Our CSS now:
#navigation { height: 3em; } #navigation ul { height: 2em; border-bottom: 1px solid #232323; margin: 0; padding: 0 1em; list-style: none; } #navigation li { float: left; height: 100%; margin-right: 1em; } #navigation a { float: left; height: 100%; padding: 0 1em; line-height: 2; font-weight: bold; text-decoration: none; color: #fff; background: #232323; border-radius: 6px 6px 0 0; } #navigation a:hover { background: #666; } #cursor { background: #e40; height: 0.5em; width: 0px; position: relative; }
Our cursor has a zeroed width and has been relatively positioned. With jQuery we have to get the left offset and the actual width of the current item to exactly position and dimension our cursor with the animate()
method:
$(function() { $('li', '#navigation').each(function() { var $li = $(this); var $a = $('a', $li); var width = $li.width(); var left = $li.position().left; $a.mouseover(function() { $('#cursor', '#navigation').animate({ width: width, left: left }, 'slow'); }); }); });
You can see the demo below.
it's like lava...xixixixi
cool cool
Just add a .stop() right before the .animate call, so that the cursor doesn't stack all the animations, but stops its current animation and goes immediately towards the currently hovered element.
hth,
gus