Close a panel when another is open


I would like to make it for if one of these panels is open, it'll close when you've clicked on another panel. I looked at some other questions similar to mine but it seems they all uses a different method for the panels.

Heres a Fiddle of it:

Heres the JS:

    var acc = document.getElementsByClassName("accordion");
    var i;

        for (i = 0; i < acc.length; i++) {
            acc[i].onclick = function() {
            var panel = this.nextElementSibling;
            if ({
   = null;
    } else { = panel.scrollHeight + "px";

I'd also like to get the '+' to change color when hovered over. Kinda like the text currently does. I cant seem to call it out right in the CSS though.

Thank You!

You can get the element that is currently active and then remove the active class like so:

// Is an array of elements matching the selector
var active = document.getElementsByClassName('active');

// If there are any matching elements and it is not the same one that has just been clicked on
if (active.length && active[0] !== this) {

One side comment (you are of course free to ignore!): for the max-height you don't need to figure out the height (unless of course it interferes with how you have your page structure already set up). You can just use some large height and since it's the max-height you are setting and not the height it will automatically go to its natural height. You can also achieve this using just CSS, including the animation, and updating the hover text on the plus sign is included below as well.

// Set regular state height to 0 and add a transition effect
.panel {
    max-height: 0px;
    transition: max-height .25s ease;

// For whatever button is active find the adjacent panel and set its max height and a transition effect
.active + .panel {
  max-height: 250px;
  transition: max-height .25s ease;

// Here is where you change the color of the active and hovered plus/minus sign,
button.accordion:hover:after {
  color: red;