Close all collapsible content at once

Viewed 55

I have the following code:

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        if (content.style.maxHeight) {
            content.style.maxHeight = null;
        } else {
            content.style.maxHeight = content.scrollHeight + "px";
        }
    });
}
.content    {
    max-height:0;
    overflow:hidden;
    transition:max-height 0.2s ease-out;
}
<button class="collapsible">First question</button>
<div class="content">First answer</div>

<button class="collapsible">Second question</button>
<div class="content">Second answer</div>

<button class="collapsible">Close all collapsible content</button>

There are two collapsible buttons called First question and Second question. You click on one of them to show the content and you click again to hide the content.

If you opened multiple collapsible contents you have to click on each of them to close all. I need a button that allows to close all at once.

But I don't know how to tell the javascript code not to close only one but every content.

Do you know how I can do that?

4 Answers

Based on the code you provided, you should just need to loop through all of your divs with the class content. From there you can apply the same maxHeight styling you do with the individual buttons.

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        if (content.style.maxHeight) {
            content.style.maxHeight = null;
        } else {
            content.style.maxHeight = content.scrollHeight + "px";
        }
    });
}

function _CollapseAll() { document.querySelectorAll(".content").forEach(el => {
    el.style.maxHeight = null;
});
}
.content    {
    max-height:0;
    overflow:hidden;
    transition:max-height 0.2s ease-out;
}
<button class="collapsible">First question</button>
<div class="content">First answer</div>

<button class="collapsible">Second question</button>
<div class="content">Second answer</div>

<button class="collapsible" onclick="_CollapseAll()">Close all collapsible content</button>

Easiest way would be to use querySelectorAll('.content') which will return a Node-List. Then you can use forEach to manipulate all elements of the Node-List at once:

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        if (content.style.maxHeight) {
            content.style.maxHeight = null;
        } else {
            content.style.maxHeight = content.scrollHeight + "px";
        }
    });
}

//closes all collapsibles
document.querySelector('.collapsible-all').addEventListener('click', function() {
  document.querySelectorAll('.content').forEach(el => el.style.maxHeight = null);
})
.content    {
    max-height:0;
    overflow:hidden;
    transition:max-height 0.2s ease-out;
}
<button class="collapsible">First question</button>
<div class="content">First answer</div>

<button class="collapsible">Second question</button>
<div class="content">Second answer</div>

<button class="collapsible-all">Close all collapsible content</button>

I would delegate

const collapse = (elem,forceClose) => {
  const content = elem.nextElementSibling;
  if (!content || !content.matches(".content")) return; // no content after the element, so leave
  if (forceClose) elem.classList.remove("active"); // passed force or nothing passed
  else elem.classList.toggle("active");
  content.style.maxHeight = elem.classList.contains("active") ? content.scrollHeight + "px" : null;
};

const buttons = document.querySelectorAll(".collapsible");
document.getElementById("container").addEventListener("click", e => {
  const tgt = e.target;
  if (!tgt.matches(".collapsible")) return; // clicked on something not a button
  if (tgt.matches(".all")) { // special button
    const close = container.querySelectorAll(".collapsible.active").length > 0;
    buttons.forEach(but => collapse(but,close)); 
  } else {
    collapse(tgt);
  }
});
.content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
.active { color: green; }
<div id="container">
  <button class="collapsible">First question</button>
  <div class="content">First answer</div>

  <button class="collapsible">Second question</button>
  <div class="content">Second answer</div>

  <button class="collapsible all">Toggle all collapsible content</button>
</div>

You can extract your commands to collapse or expand an item into functions, to be able to reuse them.

Then you simply reuse your coll variable and pass all items from coll to your collapse() function.

You should give the Collapse All button another class to not include it in the group of elements to close.

The following code uses some more modern features like Arrow Functions, and most importantly querySelectorAll() because it allows to use the quick forEach() instead of counting i’s.

Also, to render the collapsible elements accessible for people with disabilities, who rely on assistive technology, I added ARIA attributes that indicate the state of the collapsible. See the Disclosure Pattern if you want to know more.

// expand a collapsible
const expand = button => {
  const content = button.nextElementSibling;
  button.setAttribute('aria-expanded', true);
  content.setAttribute('aria-hidden', false);
  content.style.maxHeight = content.scrollHeight + 'px';
};

// close a collapsible
const collapse = button => {
  const content = button.nextElementSibling;
  button.setAttribute('aria-expanded', false);
  content.setAttribute('aria-hidden', true);
  content.style.maxHeight = null;
}

const coll = document.querySelectorAll('.collapsible');

// implement each collapsible
coll.forEach(btn => {
  btn.addEventListener('click', function() {
    if (this.classList.toggle('active')) {
      // now it’s expanded (active)
      expand(btn);
    } else {
      // now it’s collapsed
      collapse(btn);
    }
  })
});

// close all collapsibles on button click
document.querySelector('.collapsible-all').addEventListener('click', () => {
  coll.forEach(btn => collapse(btn));
});
.content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
<button class="collapsible" aria-expanded="false" aria-controls="first-answer">First question</button>
<div class="content" id="first-answer">First answer</div>

<button class="collapsible" aria-expanded="false" aria-controls="second-answer">Second question</button>
<div class="content" id="second-answer">Second answer</div>

<button class="collapsible-all">Close all collapsible content</button>

Related