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';
}
}
};
2
Answers
Finally, the solution is below:
Using the browser’s console on the page, I used the following to open the first accordion:
Yes, a loop is possible too: