.not () function does not work correctly

1

I have the following code HTML :

<div id="mini-cart" class="mini-cart dropdown is-not-empty">
    <span class="ic-cart"></span> 
    <span class="count-cart" style="display:none;"><br><br></span>
    <strong class="minhaCart">minha <span class="compraCart">COMPRA</span></strong>
    <span class="caret-cart"></span><br>
    <div id="header-cart" class="mini-cart-content dropdown-content left-hand skip-content skip-content- -style block-cart block" style="display: none;">
        <span class="msg-carrinho-vazio">&nbsp;&nbsp;Seu carrinho está vazio :(&nbsp;&nbsp;&nbsp;</span>
    </div>
</div>

And the following code jQuery :

$j('#mini-cart').not('#header-cart').on('click',function(){
    alert('Teste');
});

What I wanted to do was that when div with id="mini-cart" was clicked, alert is displayed, however, if div with id="header-cart" that is inside it is clicked, alert can not be displayed.

    
asked by anonymous 09.04.2018 / 20:41

1 answer

1

In your case it will not be possible to do this in the selector, but you can check this in function . The click brings with it information about who triggered the event among other things (read more here: event click ), it is possible to identify if the click came from the element you need, and if not, do not execute the code or even cancel the event (with stopPropagation which is a method of the event, see here: stopPropagation ). Look at this example (I have adapted a little bit of its% to make each element more evident).

$('#mini-cart').click(function(e) { 
  // recuperar o evento, pelo parâmetro 'e' ou 'event'
  e = e || event;
  // recurar o elemento que gerou o evento
  var target = e.target || e.srcElement;
  
  console.log ('Você clicou no ' + target.id);
  alert ('Você clicou no ' + target.id);
  
  if (target.id != 'mini-cart') {
  	// Se clicou em outro elemento dentro de #mini-cart, cancelo o click
      e.stopPropagation();
      return false;
  }
  
  console.log('Continuando com o evento click...');
  alert('Continuando com o evento click...');
 });
.mini-cart {
  width: 500px;
  height: 300px;
  background-color: yellow;
  padding: 50px;
}

.mini-cart-content {
   width: 400px;
   height: 200px;
   background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="mini-cart" class="mini-cart dropdown is-not-empty">
    <span class="ic-cart"></span> 
    <span class="count-cart" style="display:none;"><br><br></span>
    <strong class="minhaCart">minha <span class="compraCart">COMPRA</span></strong>
    <span class="caret-cart"></span><br>
    <div id="header-cart" class="mini-cart-content dropdown-content left-hand skip-content skip-content- -style block-cart block">
        <span class="msg-carrinho-vazio">&nbsp;&nbsp;Seu carrinho está vazio :(&nbsp;&nbsp;&nbsp;</span>
    </div>
</div>
    
10.04.2018 / 13:36