javascripttoggleclass

how to switch between classes in JS


I'm new in JS and I'm trying to resolve some menu issue. If I click on div "work", menu "work" opens. If I click again is closing. The same with "about".

The code is this:

$(function () {
    $('#work').on('click', function (){
        $('.view').toggleClass('openwork');
    })
});


$(function () {
    $('#about').on('click', function (){
        $('.about').toggleClass('openabout');
    })
});

everything's fine, but now I want to toggle the opened menus(classes). If I have "work" opened, I want get it closed when when I open "about".

I tried to use the same functions with inverted classes, but it doesn't work!

So, how can I make it work?


Solution

  • I believe you are looking for something like this:

    $(function () {
        $('#work').on('click', function (){
            $('.view').toggleClass('openwork');
            $('.about').removeClass('openabout');
        })
    });
    
    
    $(function () {
        $('#about').on('click', function (){
            $('.about').toggleClass('openabout');
            $('.view').removeClass('openwork');
        })
    });
    

    When you click one of the menus it will toggle its state (so open if closed and close if opened) and the other one will close or stay closed.