Bst_coder
Bst_coder

Reputation: 131

jQuery - Remove class from a div when we click tap on another div

jQuery(document).ready(function() { 
    if(jQuery(window).width() < 768){
        jQuery('.nb-team-grid').on('click', function(e){
            jQuery(this).toggleClass('test');
        });
    }
})

Hey guys I need to do an interaction. When we click on a div a class need to add and when we click again the class should remove it's self. I did that, you can see that code above. And one more thing I need to is, I'm repeating the div many times based on the design. So If we click on any div the class should automatically be removed from the div which we clicked just before. Check this link for more clarification. Thanks :)

http://dev.netbramha.in/projects/test-coder/test.html Click on each and every grid you see in this link

Upvotes: 1

Views: 214

Answers (1)

Mohammad
Mohammad

Reputation: 21489

Select sibling elements and remove target class from them

$('.nb-team-grid').on('click', function(e){
  $(this).toggleClass('test').siblings().removeClass('test');
});
.test {color:red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nb-team-grid">nb-team-grid</div>
<div class="nb-team-grid">nb-team-grid</div>
<div class="nb-team-grid">nb-team-grid</div>
<div class="nb-team-grid">nb-team-grid</div>

If .nb-team-grid isn't sibling use bottom code

$('.nb-team-grid').on('click', function(e){
  $(this).toggleClass('test')
  $(".nb-team-grid").not(this).removeClass('test');
});

Upvotes: 5

Related Questions