Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a sliding animation on menu hover with jQuery?

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:

http://jsfiddle.net/8EvhK/

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!

like image 231
user1461645 Avatar asked Jun 17 '12 09:06

user1461645


1 Answers

  1. Add an element to the menu using jquery's append.

    $('ul').append('<div id="slider"></div>');
    
  2. On hover of any menu item, animate this new element to the horizontal position and width 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
        });
    });
    
  3. 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});
    
  4. 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/

like image 134
danijar Avatar answered Sep 16 '22 15:09

danijar