简体   繁体   中英

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';
    }
  }    
 };

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.
    }
}

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;
        }
      });
    });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM