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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.