jQuery: Wordpress dynamic menu

Yesterday evening I found a nice Wordpress theme with an interesting, cursor-driven effect on the main menu made with CSS. I decided to recreate it with the aid of jQuery in order to get the maximum benefit from its effects. Let's see the details.

Our starting HTML structure:

<div id="navigation">
	<ul id="nav">
		<li><a href="#">Home</a></li>
		<li><a href="#">Articoli</a></li>
		<li><a href="#">About</a></li>
		<li><a href="#">Contatti</a></li>
		<li><a href="#">Demo</a></li>
		<li><a href="#">Portfolio</a></li>
	</ul>
</div>

Inside navigation we'll add the following structure with jQuery:

<div id="cursor-wrapper">
	<div id="cursor"></div>
</div>

We need two values: the overall width of each link and the left offset of each list item. For the offset, the list must be relatively positioned to get consistent values:

#navigation {
	width: 50%;
	margin: 2em auto;
	font: 100% Georgia, serif;
}

#nav {
	margin: 0;
	padding: 0 0 0 1em;
	list-style: none;
	height: 2em;
	width: 70%;
	position: relative;
}

#nav li {
	float: left;
	margin-right: 0.5em;
	height: 100%;
	line-height: 2;
}

#nav a {
	color: #555;
	text-decoration: none;
	float: left;
	height: 100%;
	padding: 0 1em;
}

#nav a:hover {
	color: #000;
	text-decoration: underline;
	background: #eee;
}

#cursor-wrapper {
	width: 70%;
	height: 10px;
	border: 1px solid;
	position: relative;
}

#cursor {
	display: none;
	background: #000;
	height: 10px;
	position: absolute;
}

When a user hovers a link, the cursor will be placed under the current link and when the user moves the mouse away, the cursor will disappear. To prevent unnecessary animation chaining, we'll use the stop() method:

$(function() {

	$('<div id="cursor-wrapper"/>').
	html('<div id="cursor"/>').
	appendTo('#navigation');

	$('li', '#nav').each(function() {
	
		var $li = $(this);
		var $a = $('a', $li);
		var left = $li.position().left;
		var width = $a.outerWidth();
		var cursor = $('#cursor');
		
		$a.hover(function() {
		
			cursor.stop(true, true).animate({
				width: width,
				visibility: 'show',
				left: left
			}, 'slow');	
		
		
		}, function() {
		
			cursor.stop(true, true).animate({
				visibility: 'hide'
			}, 'slow');	
		
		
		
		});
		
	
	
	});	


});

We use outerWidth() to get the link's width because we need to take into account also margins, padding and borders. You can see the demo below.

Demo

Live demo

Comments are closed.