How to create a sliding animation on menu hover with jQuery?
-
Add an element to the menu using jquery's
append
.$('ul').append('<div id="slider"></div>');
-
On
hover
of any menu item,animate
this new element to the horizontalposition
andwidth
of the menu item which fired 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 the slider to its initially 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 some 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/
user1461645
Updated on June 15, 2022Comments
-
user1461645 almost 2 years
I've seen this on plenty of websites but I'm not sure if I'll be able to explain it.
Sometimes there are sliding elements in navigation, just like arrow under menu items that is sliding when user hovers over different menu links etc.
Here's 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 I'll be able to 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:
Buttons background becomes red on hover. I want this background to slide and transform (width) between these buttons as I hover.
How to do something like that? I've been looking for tutorials, but no luck.
Thanks a lot!