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
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>If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With