How to create a rolling animation on hover using jQuery?

I have seen this on a large number of sites, but I'm not sure if I can explain it.

Sometimes there are sliding elements in navigation, just like an arrow in menu items that slides when the user hovers over different menu links, etc.

Here is a simple menu:

<ul> <li><a href="#">Link 1</a></li> <li><a href="#">Link number 2</a></li> <li><a href="#">Link 3</a></li> <li><a href="#">Link something 4</a></li> <li><a href="#">Link 5</a></li> </ul> 

And some jQuery (I know that I can get the same effect with simple css: hover):

 jQuery('ul li a').hover(function() { jQuery('a').removeClass('active'); jQuery(this).addClass('active'); }); 

Also, working jsfiddle:

http://jsfiddle.net/8EvhK/

The background of the buttons turns red on hover. I want this background to slide and change (width) between these buttons when I hover over.

How to do something like this? I was looking for textbooks but no luck.

Thank you so much!

+7
source share
2 answers
  • Add an item to the menu using jquery append .

     $('ul').append('<div id="slider"></div>'); 
  • In the hover any animate menu animate this new item will be displayed in the horizontal position and width of the menu item that triggered the event.

     $('ul li a').hover(function(){ var left = $(this).parent().position().left; var width = $(this).width(); $('#slider').stop().animate({ 'left' : left, 'width' : width }); }); 
  • Reset slider to its original state.

     var left = $('ul li:first-child a').parent().position().left; var width = $('ul li:first-child a').width(); $('#slider').css({'left' : left, 'width' : width}); 
  • Add CSS.

     #slider { position:absolute; top: -5px; left: 0; height: 100%; width: 0; padding: 5px 15px; background-color: #f00; z-index:-1; } 

Here is a working fiddle: http://jsfiddle.net/5wPQa/2/

+14
source

You can achieve this effect with CSS transitions :

 ul li {   display:block;   padding: 5px 15px;   background-color: #333;   color: #fff;   text-decoration: none;   width:50%;   -moz-transition: width 1s; /* Firefox 4 */   -webkit-transition: width 1s; /* Safari and Chrome */   -o-transition: width 1s; /* Opera */ } ul li:hover{   width:100%; } 

Here is an example .

-one
source

All Articles