0

When I click anything on the page, other than .card I want my function to fire. It works perfectly, however, if I have a <h2>hello</h2> inside my .card and I click on that, it also fires.

How do I get my jQuery to not fire if all/any elements inside .card are clicked, including .card?

Here is my code:

$('body').click(function(evt){    
   if(!$(evt.target).is('.card')) {
      $('.card').removeClass('active');
      $('.offer2').addClass('active');
    }
 });
devHensh
  • 49
  • 1
  • 10
  • Just do an extra check for closest `.card`. If there isn't a parent card then you know you didn;t click on the card – Huangism Jan 30 '20 at 20:00
  • 1
    Does this answer your question? [How do I detect a click outside an element?](https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element) – Heretic Monkey Jan 30 '20 at 20:05

2 Answers2

1

Check if the clicked item is inside of card or not

$(evt.target).closest(".card").length == 0 checks if there is a parent card, if the length is 0 then you know you did not click inside of a card

$('body').click(function(evt){    
   if($(evt.target).closest(".card").length == 0) {
      console.log("hi");
    }
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="card">
  <h2>not hi</h2>
  not hi
</div>

<h1>hi</h1>

Alternatively you could also do something like this, negate the click for .card, by returning false, anything inside of card also gets trapped

$('body').click(function(evt) {
  console.log("hi");
});

$('.card').click(function(e) {
  return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="card">
  <h2>not hi</h2>
</div>

<h1>hi</h1>
Huangism
  • 16,278
  • 7
  • 48
  • 74
0

When cliked on an element an event object passed to the function like function(evt) The event evt has a property target which contain the current element and its parents element html. So when a click event fired, we need to check for the closest element which have a specific class/ID like card. If the target property have not any closest element with class card then it means we clicked outside the card element.

   $('body').on('click', function(evt){    
      if($(evt.target).closest('.card').length<=0){
//Write your code here. 
console.log('Clicked out side Card');

    }
     });
Faraz Babakhel
  • 654
  • 5
  • 14