I'm actually using this button group structure with bootstrap. Now I need to add class active to each button when I click on it. And remove from it when I click on another button.
This is my HTML structure, is something like that:
<body>
<div id="header">
<div class="logo">Prova<span class="sec-logo">toscana</span>15</div>
<div class="bottoni">
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default" id="b1">12345</button>
<button type="button" class="btn btn-default" id="b2">12345</button>
<button type="button" class="btn btn-default" id="b3">12345</button>
<button type="button" class="btn btn-default" id="b4">12345</button>
<button type="button" class="btn btn-default" id="b5">12345</button>
<button type="button" class="btn btn-default" id="b6">12345</button>
</div>
</div>
</div>
</body>
Someone who could help me? Thanks.
className = "myclass"; Example 1: In this code change the class of the button from “default” to “changedClass” using the onclick event which in turn changes the background color of the button from RED to GREEN.
If you have it applied to an element but want to remove it from an element after a designated amount of time has passed, you can do so by using jQuery's . setTimeout() method. var header = $('#header'); header. addClass('blue'); setTimeout(function() { header.
jQuery Manipulating CSSaddClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements.
if .active
class should not be removed from active button after clicking on it please use addClass
instead of toggelClass
$("#header .btn-group[role='group'] button").on('click', function(){
$(this).siblings().removeClass('active')
$(this).addClass('active');
})
jsfiddle example
it is also good practice to narrow buttons selection, I used #heade
id and .btn-group[role='group']
which makes script applied only on buttons inside all button groups iside <div id="header"></div>
and here you have .active
class definition:
.btn.active{
background-color: red;
}
You are looking for something like:
$('.btn').on('click', function(){
$(this).siblings().removeClass('active'); // if you want to remove class from all sibling buttons
$(this).toggleClass('active');
});
Check jsFiddle
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