I have this html accordion code:
<div class="accordion_container">
<div class="container">
<div class="accordion">
<button class="header">
Úvod
<i class="icon"></i>
</button>
<div class="body">
Lorem Ipsum
</div>
</div>
<div class="accordion">
<button class="header">
Závěr
<i class="icon"></i>
</button>
<div class="body">
Lorem Ipsum
</div>
</div>
</div>
and this script:
<script>
let accordion_btns = document.querySelectorAll('.accordion_container .accordion .header'),
accordion_bodys = document.querySelectorAll('.accordion_container .accordion .body');
if(accordion_btns && accordion_bodys)
{
accordion_btns = Array.isArray(accordion_btns) ? accordion_btns : Object.values(accordion_btns);
accordion_btns.forEach(accordion_btn=>{
accordion_btn.addEventListener('click', function(){
process_accordion(this);
});
});
function process_accordion(x) {
set_height_0();
let next_sibling = x.nextElementSibling;
if(next_sibling.offsetHeight>0)
{
next_sibling.style.height = '0px';
x.closest('.accordion').classList.remove('active');
} else {
next_sibling.style.height = next_sibling.scrollHeight+30+'px';
x.closest('.accordion').classList.add('active');
}
}
function set_height_0() {
accordion_bodys = Array.isArray(accordion_bodys) ? accordion_bodys : Object.values(accordion_bodys);
accordion_bodys.forEach(accordion_body=>{
accordion_body.style.height = '0px';
accordion_body.closest('.accordion').classList.remove('active');
});
}
}
</script>
I was trying from all my strengh and using all my beginner brain power, but I can't figure out, how to modify this code so the first accordion is active when I load the page. I tried adding the active class to into the html but the only part of the accordion is open when i load the page.
The best way to do this is using the details / summary, where you do not need to use javascript. See MDN documentation here.
You can then assign an attribute open="true" to the that you want
<div class="accordion_container">
<div class="container">
<details class="accordion" open="true">
<summary class="header">
Úvod
<i class="icon"></i>
</summary>
<div class="body">
Lorem Ipsum
</div>
</details
</div>
<div class="container">
<details class="accordion">
<summary class="header">
Závěr
<i class="icon"></i>
</summary>
<div class="body">
Lorem Ipsum
</div>
</details
</div>
</div>