Я сделал аккордеон, используя ванильный JS.Там 99%, но при первом нажатии на аккордеон он не активируется.
data-attribute
не устанавливается на true
до второго щелчка.
JS
код приведен ниже и в ссылке есть рабочий пример.
// Get the DOM element.
const accordions = Array.from(document.querySelectorAll('.js-
accordion'));
const handleClick = accordion => () => {
// Here we set the data attribute of the selected accordion.
const selectedState = accordion.dataset.selected;
/**
* If the selected accordion's data attribute equals true –
* then we set it to false.
*/
accordion.dataset.selected = (accordion.dataset.selected === 'true') ? 'false' : 'true'; // eslint-disable-line no-param-reassign
// Set variables
const container = accordion.querySelector('.js-accordion__container');
const body = accordion.querySelector('.js-accordion__body');
const unit = 'px';
/**
* When the state of the accordion is set to true
* we return the height of the content and
* and set the collapsible state to true.
*/
if (selectedState === 'true') {
container.style.height = `${body.offsetHeight + unit}`;
accordion.setAttribute('aria-expanded', true);
} else {
container.style.height = null;
accordion.setAttribute('aria-expanded', false);
}
};
// Bind the event listener.
accordions.map(accordion => accordion.querySelector('.js-
accordion__trigger').addEventListener('click',
handleClick(accordion)));
Пример CodePen: