Accordion: Apply Same Class to the Parent and Child

Viewed 95

I currently have a working accordion for my navigation that I'm fairly happy with. I have it so when the parent is clicked, it applies a class (is-active) to the next sibling aka the '.submenu'. I'm struggling to figure out how to apply the same class to the parent as well, well the parents 'a' link (in html it's "a.accordion-item").

Basically I have it in my CSS that when 'is-active' is also applied to 'accordion-item', it will rotate the '+' into an 'x'.

Any help is appreciated, thank you! I'm also (trying) to self teach JS/Jquery so feel free to elaborate!

Full code on CodePen.

JS Code:

let accordionIsActive = "is-active";
let accordionParent = document.querySelectorAll(".accordion-item");
for (let i = 0; i < accordionParent.length; i++) {
  accordionParent[i].addEventListener("click", toggleAccordionUL, false);
}

function toggleAccordionUL(e) {
  // Prevent default link function on parent.
  e.preventDefault();
 
  let accordionGroup = document.querySelector("." + accordionIsActive);
  let sameElem = false;
  
  if (accordionGroup) {
    closeAccordion(accordionGroup);
    sameElem = accordionGroup.previousElementSibling === e.target;
  }

  if (!sameElem) {
    let accordionUL = e.target.nextElementSibling;
    openAccordion(accordionUL);
  }
}

function closeAccordion(accordionGroup) {
  accordionGroup.classList.remove(accordionIsActive);
  accordionGroup.style.maxHeight = 0;
}

function openAccordion(accordionUL) {
  accordionUL.classList.add(accordionIsActive);
  accordionUL.style.maxHeight = accordionUL.scrollHeight + "px";
}

let defaultPanel = document.querySelector(".submenu");
if (defaultPanel) {
  defaultPanel.classList.remove(accordionIsActive);
  /* setTimeout(openAccordion,1000,defaultPanel); */
}
0 Answers
Related