javascriptjqueryaccordiontoggleclass

Trying to only show header when accordion menu is not active


I have been at this problem for days now, and I know it is a simple fix but I just can't get it!

Right now, the header to my site is displayed, but once an accordion item is clicked the header is hidden, but I am trying to make it that if none of the accordion items are active, display the header again.

Here is the code I have so far:

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

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    $('.heading').hide(); 
    var active = document.querySelector(".accordion.active");
    if (active && active != this) {
      active.classList.remove("active");
      active.nextElementSibling.classList.remove("show");
    } 
    this.classList.toggle("active");
    this.nextElementSibling.classList.toggle("show");
  } 

};

I just need to make the heading display when nothing is active! Thank you!


Solution

  • I assume that accodion is opening one tab at a time. which means when you click on one active one, it close all set. If this is true, we can simply check when active element is clicked and in that case show the "heading"

    var acc = document.getElementsByClassName("accordion");
    var i;
    
    for (i = 0; i < acc.length; i++) {
      acc[i].onclick = function() {
        $('.heading').hide(); 
        var active = document.querySelector(".accordion.active");
    if (active && active == this) {
          $('.heading').show(); 
        }     
    if (active && active != this) {
          active.classList.remove("active");
          active.nextElementSibling.classList.remove("show");
        } 
        this.classList.toggle("active");
        this.nextElementSibling.classList.toggle("show");
      } 
    
    };