'How to keep one accordion item always open in Bootstrap 5?
Solution 1:[1]
You need to set a watcher on all accordion items and check if any of them are open.
If none is open then open the first one.
$('#accordion-id .collapse').each((i, e) =>
$(e).on('hidden.bs.collapse', () => {
// check if an accordion item is expanded
let isExpanded = false;
$('#accordion-id [aria-expanded]').each((i, element) => {
if ($(element).attr("aria-expanded") === 'true') {
isExpanded = true;
}
});
// show the first accordion item
if (!isExpanded) {
$('#btn-firs-accordion-id').click();
}
})
);
Solution 2:[2]
I found a solution for the Bootstrap 4 versione but none for Bootstrap 5.
After a while I was able to solve the problem with this code:
<script>
const accordions = document.querySelectorAll(".accordion-collapse");
let opening = false;
accordions.forEach(function (el) {
el.addEventListener("hide.bs.collapse", (event) => {
if (!opening) {
event.preventDefault();
event.stopPropagation();
} else {
opening = false;
}
});
el.addEventListener("show.bs.collapse", (event) => {
opening = true;
});
});
</script>
I'm not an expert js developer so I know it's not the most elegant solution but at least it solved my issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicolas PALLAS |
| Solution 2 | Juan |

