Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

527
Visualizações
How to keep one accordion item always open in Bootstrap 5?

I have the first accordion item opened by default so what I wanted to do was to always have at least one opened at any time (so the picture on the side keeps a decent aspect ratio). By default I can close all of them and when I open a new one, all the others get closed.

enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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();
        }
    })
);

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda