How to place 2 events. click() on a button

Asked

Viewed 130 times

0

I am making an administrator panel where you have the following options of Buttons

Dashboard class="dashboard-button"

Settings class="settings-button"

Contents class="contents-button"

Feedback class="feedback-button"

They all have the same id id="options"

And when you click on akgum button, a Nav appears below with the link options

And my jquery is like this

$(".dashboard-button").click(function(){
    $(".navbar-dashboard").addClass("active");
});

Obs the class navbar-dashboard is the one that will appear when you click the button Already the class active is the one with the css display bloxk because initially the navbar has None display

Summarizing what I want is, by clicking the button, the navbar appears And if the user clicks the same button again, it disappears

Could someone enlighten me? I’m at a time cracking my head to find a solution kkkkk

  • 2

    from what I understand it is enough for you to replace the addClass("active") method with toggleClass("active")

  • 1

    The global attribute id defines an identifier for an element, should be unique and unique throughout the document.MDN Webdocs id

2 answers

0

You can check if there is a class active with hasClass. If it exists, remove it with removeClass. And if it doesn’t exist, add it with addClass.

$(".dashboard-button").click(function(){
    if ($(".navbar-dashboard").hasClass("active")) {
        $(".navbar-dashboard").removeClass("active");
    } else {
        $(".navbar-dashboard").addClass("active");
    }
});

I made an example working: https://jsfiddle.net/8m75jozh/1/

0

Just exemplifying what the Gabriel José de Oliveira said there in the comments:

$(".dashboard-button").click(function(){
    $(".navbar-dashboard").toggleClass("active");
});

The function toggleClass adds class when it does not exist and removes class when it exists.

More information: https://api.jquery.com/toggleClass/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.