David Hope
David Hope

Reputation: 1536

Javascript: close all accordions when one is clicked?

I'm basically trying to close all the accordions close and only keep one of them open which was clicked.

So, in short term, only keep one tab open.

This is what I have so far:

https://jsfiddle.net/gymzfg9r/2/

and this is the javascript:

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

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        this.classList.toggle("active");
        this.nextElementSibling.classList.toggle("show");
  }
}

Could someone please advise on this?

Upvotes: 0

Views: 926

Answers (2)

rule
rule

Reputation: 281

this do the job , but i am pretty sure this is a terrible way to do it, just cant recall a better one right now

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

function closeEverything() {
    var openElements = document.getElementsByClassName("active");
  if(openElements.length) {
    for(var i = 0; i < openElements.length; i++) {
        openElements[i].nextElementSibling.classList.toggle("show");
        openElements[i].classList.toggle("active"); 
     }
    }
}

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
            if(this.classList.contains('active')) {
            this.classList.toggle('active');
            this.nextElementSibling.classList.toggle('show');
        } else {
                closeEverything();
            this.classList.toggle("active");
            this.nextElementSibling.classList.toggle("show");
        }
    }
}

Upvotes: 1

WantToDo
WantToDo

Reputation: 441

insert code for close others:

  this.classList.toggle("active");

  var arr = document.getElementsByClassName("show");
  for (j = 0; j < arr.length; j++) {
      if(this.nextElementSibling != arr[j])
         arr[j].classList.toggle("show");
  }


  this.nextElementSibling.classList.toggle("show");

Upvotes: 1

Related Questions