Submit your widget

Awesome Animation menu with jquery

Created 13 years ago   Views 13723   downloads 3170    Author css3forum
Awesome  Animation menu with jquery
View DemoDownload
61
Share |

This is an Awesome  Animation menu with jquery.

First off all, the problem was those background lines,If you just set background separately to all your list tags you end with lines not in order

To fix this you can just hardcode all background position in css, but then your menu will be static and if you add some new item you need to set those positions again. And this I think you will not be glad to do all over again. So we need some Jquery script.

First we add some css style to menu:

#menu {
	float: left;
	width: 800px;
	list-style: none;
	line-height: 33px;
	background: url('../images/menu_bg.gif') no-repeat top left;
	border-top: 1px solid #0b558e;
	border-bottom: 1px solid #0b558e;
	margin: 0;
	padding:0;
}

#menu li {
	float: left;
	border-left: 1px solid #1b76bc;
}

#menu li a {
	float: left;
	font-size: 1.2em;
	color: #fff;
	border-left: 1px solid #3993da;
	text-decoration: none;
	background: url('../images/menu_bg.gif') no-repeat top left;
}

#menu li:first-child { border: none; }
#menu li:first-child a { border: none; }

Then let’s start write script.

var width = 0;
$('#menu li').each(function() {
	width += $(this).width()+1;
});

var padding = parseInt((($('#menu').width() - width) / $('#menu li a').length)/2);
var pixLeft = ($('#menu').width() - width)-(padding*$('#menu li a').length*2)

This will count all menu white (width), what padding should be add to list items (padding) and how many pixels left (pixLeft) because you can add only integer number in padding. Note that in line “width += $(this).width()+1;” plus one means that you add 1px border to list tag, if you do not have borders just delete plus one.

And now we will add automatic background positioning and padding so if you add new item or delete one it calculate it for you.

$('#menu li a').each(function(index) {
	if (index+1 != $('#menu li a').length) {
		$(this).css('padding', '0 '+padding+'px');
		$(this).css('background-position', '-' + $(this).position().left + 'px 0');
	} else {
		padding = padding + (pixLeft/2);
		$(this).css('padding', '0 '+padding+'px');
		$(this).css('background-position', '-' + $(this).position().left + 'px 0');
	}
});

You can see that all lines are nice in order. And now some extra if you want – for little animation just add this:

$('#menu li a').mouseover(function(){
		$(this).stop().animate({ backgroundPosition: '-' + $(this).position().left - 129 + 'px -35px'}, 2000)
	.mouseout(function(){
		$(this).stop().animate({ backgroundPosition: '-' + $(this).position().left + 'px 0'}, 2000)
	})
});

That’s all,hope you like it.

The article source:http://www.css3forum.com/all_articles/nice-jquery-menu-animation/