Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hover/click class

I'm creating a menue for a site. I'm trying to accomplish a hover and click effect on links. I want the hover event on the elements a of the list to trigger a color animation and add the class 'active'. If the click and hover events are triggered I want to assign the same class to that element. Problem is that the class must be removed once the element is not hovered and other element is clicked. This is the code:

<div id="menu">
        <ul>
            <li><a href="#" id="btHome">HOME</a></li>
            <li><a href="#" id="btAbout">NOSOTROS</a></li>
            <li><a href="#" id="btGallery">GALERIA</a></li>
            <li><a href="#" id="btContact">CONTACTO</a></li>
        </ul>
</div>

And the CSS:

.active{
    color:#0CF;
    background-image:url(../img/select.png);
    background-repeat:no-repeat;
    background-position:right center;
}

jQuery:

$("#menu ul li a").hover(function() {
    $(this).stop().animate({color: "#0CF"}, 250); //I have the jQueryUI plugin
},function() {
    $(this).stop().animate({color: "#FFF"}, 100);
});

$("#menu ul li a").click(function() {
    $(this).toggleClass('active', 150);
});
like image 727
coffee Avatar asked Jan 26 '26 14:01

coffee


1 Answers

You can continue chaining here, no need to have 2 separate selectors:

var allLinks = $("#menu ul li a").hover(function() {
    $(this).stop().animate({color: "#0CF"}, 250);
},function() {
    var $this = $(this);
    if(!$this.hasClass('active')) // if it is not the active link
        $this.stop().animate({color: "#FFF"}, 100);
}).click(function() {
    allLinks.removeClass('active');
    $(this).toggleClass('active', 150); // may need to adjust the timing here for better UX
});

Notice in the click handler remove any active class first.

like image 109
Josiah Ruddell Avatar answered Jan 28 '26 04:01

Josiah Ruddell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!