Skip to content

Instantly share code, notes, and snippets.

@b-aleksei
Last active August 27, 2021 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b-aleksei/7ab22760bfe5243cf2949c934ab26e74 to your computer and use it in GitHub Desktop.
Save b-aleksei/7ab22760bfe5243cf2949c934ab26e74 to your computer and use it in GitHub Desktop.
accordion-classic
const accordionToggle = (selector) => {
const accordion = document.querySelector(selector);
if (!accordion) return;
let previousContent = null;
let previousTitle = null;
accordion.addEventListener('click', (e) => {
const accTitle = e.target.closest('.accordion__title');
if (accTitle) {
const accContent = accTitle.nextElementSibling;
if (previousContent) {
previousContent.style.maxHeight = '0';
previousTitle.setAttribute('aria-expanded', 'false');
}
if (previousContent === accContent) {
previousContent = null;
previousTitle = null;
return;
}
accTitle.setAttribute('aria-expanded', 'true');
accContent.style.maxHeight = accContent.firstElementChild.offsetHeight + 'px';
previousContent = accContent;
previousTitle = accTitle;
}
});
};
accordionToggle('.accordion');
/*<div class="accordion">
<div class="accordion__item">
<h2 class="accordion__title">
<button id="accordion1" type="button" aria-expanded="false" aria-controls="content1"></button>
</h2>
<div id="content1" class="accordion__content" aria-labelledby="accordion1">
<div class="accordion__content-inner"></div>
</div>
</div>
</div>
.accordion {
background: white;
}
.accordion__title {
position: relative;
display: flex;
justify-content: space-between;
cursor: pointer;
&::after {
content: "";
width: 6px;
height: 6px;
margin: 10px 0 0 15px;
border-right: 2px solid currentColor;
border-bottom: 2px solid currentColor;
flex-shrink: 0;
transform: rotate(45deg);
transition: transform .3s;
transform-origin: 66% 66%;
}
&[aria-expanded="true"] {
&::after {
transform: translateY(-50%) rotate(-135deg);
}
}
}
.accordion__content {
max-height: 0;
overflow: hidden;
transition: max-height .3s;
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment