Toggle Active Class On A Button But Maintain State Of Other Buttons
I've read Javascript / JQuery Toggle Active Class between 2 buttons on a button group. However I have a situation where I want to toggle the active class on a button being clicked,
Solution 1:
You can run some conditional work for your input to add and remove class on the input you click:
$( "input" ).click(function() {
var $this = $(this);
if ($this.hasClass("active")) {
$this.removeClass("active");
} else {
$this.addClass("active");
}
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script><!-- Button 1 --><inputtype="button"name="btn1"class="filter-btn active"><!-- Button 2 --><inputtype="button"name="btn2"class="filter-btn"><!-- Button 3 --><inputtype="button"name="btn3"class="filter-btn active"><!-- Button 4 --><inputtype="button"name="btn4"class="filter-btn">
You can check by inspecting the elements of the inputs
once clicking them that the active
class would be added and removed if clicked
Update
If you would like to slim the JavaScript down further, you can use toggleClass():
$( "input" ).click(function() {
$(this).toggleClass("active");
});
Post a Comment for "Toggle Active Class On A Button But Maintain State Of Other Buttons"