Search code examples
jquerysidebar

add class when click on a div


I'm trying to make a sidebar with a navigation menu that will expand/collapse when I click on a div.

$(document).ready(function() {     
$('.btn-nav').click(function(){     
    $('.sidebar').addClass('expand');    
},     
function(){    
    $('.sidebar').removeClass('collapse');     
});
}); 

When I replace the click function to a hover function it works fine. But now it won't work. Does anyone have an idea what I'm doing wrong?


Solution

  • You need to do this:

    $(document).ready(function () {
        $('.btn-nav').click(function () {
            $('.sidebar').toggleClass('expand').toggleClass('collapse');
        });
    });
    

    If you have a look at the click() API Documentation, you will find that it takes only one function but the hover() takes one or two handlers function, executed when the mouse pointer enters and leaves the elements.