CodeForGood
CodeForGood

Reputation: 749

First accordion to be made open by default either by JavaScript or CSS

I got 3 accordions in a Shopify product page out of which I intend to keep the first one expanded by default on page load. Once the page loaded, clicking other accordions should close all previously opened ones. I want to do it only with pure JavaScript(no libraries like jQuery) or CSS. My code below just ensures the first accordion is shown expanded. Could you please help correct my code after having a look at the accordions in the page https://wv3yau73hiyf9fhv-458195004.shopifypreview.com?

 window.onload = function() {
  var accItem = document.getElementsByClassName('accordion__item');
  // Keep the first accordion open by default.
  for (i = 0; i < accItem.length; i++) {
    console.log("Within first for loop");
    accItem[0].click();
    accItem[i].addEventListener('click', toggleItem, false);
  }
  function toggleItem() {
    var itemClass = this.parentNode.className;
    for (i = 0; i < accItem.length; i++) {
      console.log("Within second for loop");
      accItem[i].className = 'accordion__item close';
    }
    if (itemClass == 'accordion__item close') {
        this.parentNode.className = 'accordion__item open';
    }
  }    
 };

Upvotes: 2

Views: 1339

Answers (2)

CodeForGood
CodeForGood

Reputation: 749

Finally, the solution is below:

  // Keep the first accordion open by default.
  let allAccordions = document.querySelectorAll(".accordion__item");
  if (allAccordions.length > 0) {
    allAccordions[0].querySelector("input[type=radio]").checked = true;
  }
  // Capture click event for the accordions
  allAccordions.forEach(element => {
    element.addEventListener('click', function() {
      let radioBtn = this.querySelector("input[type=radio]");
      let clickedRadioName = radioBtn.getAttribute("name");

      allAccordions.forEach(element => {
        let elementRadioBtn = element.querySelector("input[type=radio]");
        let elementRadioName = elementRadioBtn.getAttribute("name");
        if ((elementRadioName != clickedRadioName) && elementRadioBtn.checked) {
          element.querySelector("input[type=radio]").checked = false;
        }
      });
    });
  });

Upvotes: 1

Paul T.
Paul T.

Reputation: 4907

Using the browser's console on the page, I used the following to open the first accordion:

let allAccordions = document.querySelectorAll(".accordion__item");
allAccordions[0].click();

Yes, a loop is possible too:

for (var i = 0; i < allAccordions.length; i++) {
    if (i == 0) {
          allAccordions[i].click();
          break; // only the first, can stop looping.
    }
}

Upvotes: 2

Related Questions