skip to Main Content

When tag link is clicked, .active will be added to that specific tag. I want when there’s .active present on the tag, the p will turn blue (.active is added to the p).

I managed to turn the p to blue. However, I’m having trouble removing the blue color and .active when the tag link is not active.

$('.tag').click(function() {
  var clicks = $(this).data('clicks');
  if (clicks) {
    $(this).addClass('active');
  } else {
    $(this).removeClass('active');
  }
  $(this).data("clicks", !clicks);
});


$('.tag').click(function() {
  var numActive = $('.active').length
  if (numActive > 0) {
    $(this).closest('.wrap').find('.filter').addClass('active');
  } else {
    $(this).closest('.wrap').find('.filter').removeClass('active');
  }
})
.tag.active {
  color: red;
}

.filter.active {
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="wrap">
  <p class="filter">filter</p>
  <div class="tag-wrap">
    <a class="tag">tag 1</a>
    <a class="tag">tag 2</a>  
    <a class="tag">tag 3</a>
  </div>
</div>

2

Answers


  1. You can combine the logic into one click handler and simplify it using toggleClass:

    $('.tag').click(function() {
      $(this).toggleClass('active');
      updateFilter();
    });
    
    function updateFilter() {
      $('.filter').toggleClass('active', $('.tag.active').length > 0);
    }
    .tag.active {
      color: red;
    }
    
    .filter.active {
      color: blue;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="wrap">
      <p class="filter">filter</p>
      <div class="tag-wrap">
        <a class="tag">tag 1</a>
        <a class="tag">tag 2</a>  
        <a class="tag">tag 3</a>
      </div>
    </div>
    Login or Signup to reply.
  2. You can try this also

    $('.tag').click(function() {
          $(this).toggleClass('active');
          $('.filter').toggleClass('active', $('.tag').hasClass('active'));
     });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search