Home > OS >  Trigger multiple actions on click with toggleClass() in jQuery
Trigger multiple actions on click with toggleClass() in jQuery

Time:02-23

I want to trigger several simultaneous actions when I click a button.

In jQuery, I use toggleClass() to show and hide the burger. Unrolling the menu on click works perfectly. What I can't do is to trigger another event simultaneously. For example, hiding an item on the page.

The behavior I want to achieve is the following: . when I click on the burger, the menu unrolls and hides the item in question . a new click on the burger brings up the menu and displays again the item that was hidden

I tried a lot of things without success.

A little help ?

CodePudding user response:

For that kind of effect, I typically add a class to whatever container contains both the menu and the thing you want to show/hide (in the worst case, they're both in body), then use CSS with a descendant selector to control the menu and the thing. Here's a basic example:

document.getElementById("menu").addEventListener("click", () => {
    document.getElementById("container").classList.toggle("the-class");
});
#menu {
    /* Normal styles for the menu */
    border: 1px solid grey;
    height: 5em;
}
.hidey-thing {
    /* Normal styles for the hidey thing if any needed */
}

#container.the-class #menu {
    /* Styles for the menu when toggled */
    height: 10em;
    border: 1px solid black;
}
#container.the-class .hidey-thing {
    /* Styles for the hidey thing when toggled */
    display: none;
}
<div id="container">
    <div id="menu">
    The menu
    </div>
    <div >
    This is the show/hide thing
    </div>
</div>

I didn't use jQuery there because I didn't see the need, but you could:

$("#menu").on("click", () => {
    $("#container").toggleClass("the-class");
});

CodePudding user response:

Do you mean:

$(document).on("click", "#trigger1", function () {
    //code here
});
  • Related