Kroi
Kroi

Reputation: 410

How to add class to the clicked button and remove a class to the previously clicked button

How will I add a class to the clicked button and remove a class to the previously clicked button. I want to have a single active button only per click

My html looks like this

<div class="nav-button">
   <button id="btn-all">All</button>
   <button id="btn-chicken">Chicken</button>
   <button id="btn-pizza">Pizza</button>
   <button id="btn-pasta">Pasta</button>
   <button id="btn-drinks">Drinks</button>
</div>

And my jquery looks like this

$('.nav-button button').on('click', function(){
     $(this).addClass("active")
})

I dont want to select the buttons one by one because this group of button is dynamic. I just only use the html example above to show my buttons in html

Upvotes: 4

Views: 1066

Answers (1)

Giorgos Betsos
Giorgos Betsos

Reputation: 72165

You can simply first remove the class from all buttons:

 $("div.nav-button button").removeClass('active');

So you can do:

$('.nav-button button').on('click', function(){
     $("div.nav-button button").removeClass('active');
     $(this).addClass("active");
})
.active {
    background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nav-button">
   <button id="btn-all">All</button>
   <button id="btn-chicken">Chicken</button>
   <button id="btn-pizza">Pizza</button>
   <button id="btn-pasta">Pasta</button>
   <button id="btn-drinks">Drinks</button>
</div>

Upvotes: 2

Related Questions