Search code examples
jqueryclickmouseentermouseleave

jquery click/mouseenter/mouseleave change class


I am tring do some effect. the defualt select word is the first li.

ul {
    list-style: none
}
.a-c {
    color: #c10603;
    cursor: pointer
}
<ul>
    <li class="a a-c">list1</li>
    <li class="a">list2</li>
    <li class="a">list3</li>
    <li class="a">list4</li>
    <li class="a">list5</li>
</ul>

when I click another li, the default will change. some code working well.

$('body').on('click','.a', function(){
    $('.a-c').removeClass('.a-c');
    $(this).addClass('.a-c')
});

Now I need another effect, when mouse hover li, the defaut li will change color into black, and the one which mouseenter will change color into the color:#c10603, some code also working.

$('body').on('mouseenter','.a', function(){
    $(this).addClass('a-c')
});
$('body').on('mouseleave','.a', function(){
    $('.a').removeClass('a-c')
});

But I also need, if mouseleave all the li, the defult li will still show color as #c10603

Some online code here http://jsfiddle.net/3rvd8qwf/1/ my problem is when i click another li and mouseleave all the li, the defualt li should change into the one which I clicked, not always the first one. Thanks.


Solution

  • Your problem can be handled by CSS alone; and one less jQuery function:

    HTML:

    <ul>
        <li class="active">List Item 1</li>
        <li>List Item 2</li>
        <li>List Item 3</li>
    </ul>
    

    CSS:

    li{
        font-size: 28px;
    }
    
    li.active{
        color: red;
    }
    
    ul:hover li{
        color: black;
    }
    
    li:hover{
        color: red !important;
    }
    

    jQuery:

    $(document).ready(function(){
        $("li").click(function(){
            $("li.active").removeClass("active");
            $(this).addClass("active");
        });
    }); 
    

    Check out the fiddle here: http://jsfiddle.net/mk779g3o/