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
You can combine the logic into one click handler and simplify it using
toggleClass
:You can try this also