简体   繁体   中英

Hover effects on list item

On my vertical navigation, I want to highlight list item which is last clicked and currently active. Highlighting is done with assigning red background to list item. I also want to highlight list item on mouse hover. Problem is when hovering on other list items, I want to temporarily remove class active from active list item, and when the mouse pointer is no longer on inactive list item, that active class is assigned to active list item back again. Here is what it looks like on JSFiddle: http://jsfiddle.net/9r3tx/2/

This is jQuery function which assigns class active to list item which is clicked:

//Add class active on click, firts li is active by default
$('.navigation li:first').addClass('active');

$(".navigation li a").click(function(e) {
    $('.navigation li').removeClass('active');
    $(this).parent().addClass('active');
}); 

This is where problem is:

//Change classes on hover
$(document).ready(function(e) { 
$(".navigation li a").hover(function(e){
    $('.navigation li').removeClass('active');
    $(this).parent().addClass('active');
});
}); 

I know that this assigns class active to hovered link, and stays like that, but I want to temporarily assign class active, which would just last for time when the pointer is above that list.

My own suggestion would be to use CSS in concert with jQuery:

$('.navigation li:first').addClass('active');

$('.navigation li').click(function(){
    $(this).addClass('active').siblings('.active').removeClass('active');
});

With the CSS:

/* overrides the red of the '.active' when the list is hovered:
*/
.navigation:hover li.active {
    background-color: #fff;
}

/*
sets the li.active colour,
ensures the colour of the li.active when it's hovered,
and colours the li elements when they're hovered:
*/
.navigation li.active,
.navigation li.active:hover,
.navigation li:hover {
    background:red;
}

JS Fiddle demo .

How about THIS simple demo which does exactly what you ask for using mouseleave

//Add class active on click, firts li is active by default
    $('.navigation li:first').addClass('active');

    $(".navigation li a").click(function(e) {
        $('.navigation li').removeClass('active');
        $(this).parent().addClass('active');
    }); 

//Change classes on hover
$(document).ready(function(e) { 
    $(".navigation li a").hover(function(e){
        $('.navigation li').removeClass('active');
        $(this).parent().addClass('active');
    });

    $(".navigation li a").on('mouseleave', function(e){ // this function for removing
        $(this).parent().removeClass('active');
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM