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

150
Visualizações
Javascript / JQuery Toggle Active Class between 2 buttons on a button group

I am using bootstrap with btn-group. There is the html:

<div class="btn-group btn-group-sm" role="group">
    <div type="button" class="btn btn-default btn-1">Button 1</div>
    <div type="button" class="btn btn-default btn-2 active">Button 2</div>
</div>

Button 2 it already active.

Currently I'm doing this to remove the active class from one and add it to another.

$('.btn-2').removeClass('active');
$('.btn-1').addClass('active');

Is this the cleanest way to do this or is there a better way so it can just toggle this active class between the two buttons?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Use:

$('.btn-group').on('click', '.btn', function() {
  $(this).addClass('active').siblings().removeClass('active');
});

I think the code is fairly self-explanatory? It simply removes any existing "active" classes from the siblings of the button you clicked, and adds that class to the clicked button.

Here's a working snippet:

$('.btn-group').on('click', '.btn', function() {
  $(this).addClass('active').siblings().removeClass('active');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="btn-group btn-group-sm" role="group">
  <div type="button" class="btn btn-default btn-1">Button 1</div>
  <div type="button" class="btn btn-default btn-2 active">Button 2</div>
</div>

over 4 years ago · Santiago Trujillo 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