em1382 em1382 - 3 months ago 5x
Javascript Question

Toggle all accordion tabs closed before opening another (only one open at a time)

I'm using JQuery and JQuery UI to build a small web application that is based around an accordion. I have the accordion logic figured out, but I'm having some trouble getting the result I want. I want all of the tabs to collapse when one is clicked, but I'm not sure how to do that.

Google didn't help me at all, before the serial downvoters nab me. Couldn't find anything on here, either.

Here is my HTML:

<button class="accordion">About</button>
<div class="panel">
<p>Blah 1</p>
<button class="accordion">Contact</button>
<div class="panel">
<label>Full Name</label>
<input type="text" />
<label>E-mail Address</label>
<input type="email" />


button.accordion {
background-color: #336699;
background: linear-gradient(-90deg, #fff, #336699, #fff);
color: #fff;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: center;
outline: none;
font-size: 15px;
transition: 0.4s;

button.accordion:not(:last-child) {
margin-bottom: 10px;

button.accordion .active,
button.accordion:hover {
background-color: #555;

div.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: 0.6 ease-in-out;
opacity: 0;

div.panel.show {
opacity: 1;
max-height: 500px;

div.column {
float: left;
width: 300px;

And finally, my JQuery:

$(function() {
$('.accordion').on('click', function() {
// Something here, maybe?
$(this).toggleClass('active', 400);
$(this).next().toggleClass('show', 400);

When I try to put something inside the callback to close all of them, it ends up getting executed immediately and the tabs don't open at all. Can someone please give me an explanation of what exactly is going on?


To achieve your expected result, use below

$(function() {
  $('.accordion').on('click', function() {

    var x = $('.accordion').hasClass('active');
    if (x) {
      $(this).toggleClass('active', 400);
      $(this).next().toggleClass('show', 400);
    } else {
      $(this).toggleClass('active', 400);
      $(this).next().toggleClass('show', 400);