Home > other >  Building Accordion in JS
Building Accordion in JS

Time:10-11

please check my js code i wanted to insert my html only once and to check that i created a condition and it worked fine but the problem is my other buttons also having the same class are affected and i have to reload my page everytime.

check codepen here: https://codepen.io/Sameed02/pen/GRdPRMP

'use strict';
const accordion = document.getElementsByClassName('item');
const btn = document.querySelectorAll('.btn');
const item = document.querySelector('.item')
const content = Array.from(accordion);



const html = `<div >
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nesciunt, dolorum! Laboriosam
    necessitatibus
    architecto voluptate omnis maxime deserunt dolore fugiat, earum nulla. Id voluptas voluptatem
    facere
    accusantium, expedita corrupti beatae temporibus Lorem.</p>
<ul>
    <li>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos, nemo!
    </li>
    <li>Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugit sunt itaque id!
    </li>
    <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Labore, inventore?
    </li>
    <li>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eum, consequatur.
    </li>
</ul>
</div>`

btn.forEach((btn, i) => {
    btn.addEventListener('click', function () {
        console.log(`btnPosition:${i}`);
        if (!document.querySelector('.hidden-box'))
            content[i].insertAdjacentHTML('beforeend', html);
    })
})

CodePudding user response:

I think you should this in 2 steps.

  1. You should create a variable to hold the index of the currently active accordion item (for instance activeAccordionIndex). Then when you click on the button you set that variable to the index of the clicked button.

  2. On the second step you loop through all of the accordion items. If the accordion item index is the same as the activeAccordionIndex, then you can "open" the accordion item. If not, you close it.

Here is a small example to show what i mean:

const items = document.querySelectorAll('.accordion__item');
let activeAccordionItemIndex = null;

items.forEach((item, index) => {
  const itemTitle = item.querySelector('.accordion__title');
  itemTitle.addEventListener('click', () => {
    item.hasAttribute('open') ?
      activeAccordionItemIndex = null :
      activeAccordionItemIndex = index

    updateAccordionUI();
  })
});

function updateAccordionUI() {
  items.forEach((item, index) => {
    if (index === activeAccordionItemIndex) {
      item.setAttribute('open', '');
    } else {
      item.removeAttribute('open');
    }
  })
}
* {
  font-family: sans-serif;
}

.accordion__item {
  border: 1px solid lightgrey;
  padding: 0 1rem;
}

.accordion__title {
  font-size: 1.5rem;
  color: grey;
}

.accordion__title:hover {
  color: blue;
  cursor: pointer;
}

.accordion__text {
  display: none;
}

.accordion__item[open] .accordion__text {
  display: block;
}
<div >
  <div >
    <p >item one</p>
    <p >item one content!!! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </div>
  <div >
    <p >item two</p>
    <p >item two content!!! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </div>
  <div >
    <p >item three</p>
    <p >item three content!!! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </div>
</div>

  • Related