Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery animating border

I have this html code

<nav id="mainNav">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>        
    </ul>
</nav>

It has the css style of this

    #mainNav { display:block; padding:5px; }
    #mainNav ul { display:block; list-style-type:none; width:500px; border-collapse:collapse; }
    #mainNav li { display:inline-block; width:100px; height:66px; text-align:center; padding-top:10px; float:left; background-color:gray; cursor:pointer; border-bottom:0px solid red; }
    #mainNav a { color:white; text-decoration:none; text-transform:capitalize; }
    #mainNav a.aHover { color:red; }

And attached to this is the JQuery code

$(document).ready(function() {
$('#mainNav li').mouseover(function() {
    var el = $(this);
    $(this).animate({
    "border-bottom-width":"+=5px"
    },{ queue: false, duration: 500 }, function() {
    el.css('border-bottom-width', '5px');   
    });
    $(this).children('a').addClass('aHover');
});
$('#mainNav li').mouseout(function() {
    var el = $(this);
    $(this).animate({
    "border-bottom-width":"-=5px"
    },{ queue: false, duration: 500 }, function() {
    el.css('border-bottom-width', '0px');   
    });
    $(this).children('a').removeClass('aHover');
});
});

Now what I want it to do is either, fade in the border colour to red and fade it out, or as written in the code, expand the border to a max of 5px on hover then deflate the border back to 0px.

Question is, as you can see I try to change the class of the LI element at the end of the animation to make sure the border goes to its max or min width, but that doesn't work, why?

How would you fade in and out the border colour?

like image 608
Callum Linington Avatar asked Oct 08 '22 23:10

Callum Linington


1 Answers

Try below,

DEMO

$(document).ready(function() {
    $('#mainNav li').hover(function() {
        var el = $(this);
        $(this).stop(true, true).animate({
            "border-bottom-width": "5px"
        }, {
            queue: false,
            duration: 500
        });
        $(this).children('a').addClass('aHover');
    }, function() {
        var el = $(this);
        $(this).stop(true, true).animate({
            "border-bottom-width": "0px"
        }, {
            queue: false,
            duration: 500
        });
        $(this).children('a').removeClass('aHover');
    });
});

Changed,

  1. mouseover event to mouseenter as it is more appropriate in your case
  2. Changed mouseenter/mouseleave to hover
  3. Changed +=5px, -=5px to 5px and 0px.
  4. Added .stop(true, true) to make sure the animation is completed and the queue is cleared.
like image 102
Selvakumar Arumugam Avatar answered Oct 12 '22 20:10

Selvakumar Arumugam