If a button has active class then it should not toggle if I click on it again. Here I have two buttons "Grid View" and "List View" I want when "Grid View" is active and still I click on it this should not toggle active class.
$('.switch-btn').click(function(e){
$('.switch-btn.grid, .switch-btn.list').toggleClass('active');
});
button.switch-btn {
border: none;
outline: none;
padding: 10px 20px;
cursor: pointer;
}
button.switch-btn.active {
background: green;
color: #FFFFFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="switch-btn grid active">Grid View</button>
<button class="switch-btn list">List View</button>
Just add checker for the class existence, like below:
$('.switch-btn').click(function(e){
const cButton = $(e.currentTarget);
if (cButton.hasClass('active'))
return;
$('.switch-btn.grid, .switch-btn.list').toggleClass('active');
});
button.switch-btn {
border: none;
outline: none;
padding: 10px 20px;
cursor: pointer;
}
button.switch-btn.active {
background: green;
color: #FFFFFF;
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<button class="switch-btn grid active">Grid View</button>
<button class="switch-btn list">List View</button>
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