Why i get unsuspected behavior when I use the if/else statements?

Viewed 62

Why when I use if/else statements I get unexpected behavior of the filters button I mean the state value of the class attribute is assigned to several buttons but not only one. When I use two if statement I get the needed behavior of buttons

 //declate states-filters
 var $all = $("#all"); //find all items
 var $active = $('#active'); //find active items
 var $completed = $("#completed"); //find completeditems

 //filter-all
 $all.on('click', function(){
     if($all.is('[class!="active"]')){ //check the element have the active value of the class

         if($completed.has('[class="active"]')){
                 $completed.removeClass('active'); $all.addClass('active')
         }
         if($active.has('[class="active"]')){
                 $active.removeClass('active'); $all.addClass('active')
         }

 }
 })
 //filter-active
 $active.on('click', function(){
     if($active.is('[class!="active"]')){ //check the element have the active value of the class


         if ($all.has('[class="active"]')) {
             $all.removeClass('active'); $active.addClass('active');
         } if ($completed.has('[class="active"]')){
             $completed.removeClass('active'); $active.addClass('active')
         }
     }
 })

 //filter-complete
 $completed.on('click', function(){
     if($completed.is('[class!="active"]')){ //check the element have the active value of the class

         if ($all.has('[class="active"]')) {
             $all.removeClass('active'); $completed.addClass('active');
             
         } if ($active.has('[class="active"]')){
             $active.removeClass('active'); $completed.addClass('active')
         }
     }
 })
<div class="states-filter">
    <p  class="state active" id="all"> All </p>
    <p  class="state" id="active"> Active </p>
    <p  class="state" id="completed"> Completed </p>
</div>

1 Answers

You don't need to use click event for all p tag .As all p tag have same class i.e : state you can use this as a selector .Then, whenever any state is click add active class to that element and remove active class from other elements using .not(this) and removeClass()

Demo Code :

var $all = $("p.state");

$all.on('click', function() {
  //p tag which is clicked add active class to that 
  $(this).addClass("active");
  //find p tag (not the one which is clicked remove active class from there)
  $(this).closest(".states-filter").find("p").not(this).removeClass("active")
})
.active {
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="states-filter">
  <p class="state active" id="all"> All </p>
  <p class="state" id="active"> Active </p>
  <p class="state" id="completed"> Completed </p>
</div>

Related