Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle class should not clicked again

Tags:

jquery

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>
like image 701
Adam Pavlov Avatar asked Mar 09 '26 06:03

Adam Pavlov


1 Answers

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>
like image 94
Fadhly Permata Avatar answered Mar 10 '26 20:03

Fadhly Permata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!