AGamePlayer
AGamePlayer

Reputation: 7736

How do I prevent parent event handler on a child node?

I have a div and it's listend by a event handler:

$('.thediv').click(function() {
  $(this).remove()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="width:500px;height:500px">
  <input type="input" style="width:100px;height:20px" />
</div>

The div would be removed if it's clicked.

However, I want to put a text input box on the div and if the user clicks the text input, the div should not be removed. Only when the user clicks the area outside the input box, the div get removed.

What can I do?

Upvotes: 0

Views: 60

Answers (3)

zer00ne
zer00ne

Reputation: 43910

In the following demo:

  1. .box is the parent element that listens for the click event.
  2. .box is also referred to as event.currentTarget because it is registered to the click event.
  3. .box is also considered this within the callback function.
  4. The event.target is the origin of the event -- the element that the user clicked.
  5. .box has an <input> child element.
  6. The callback function simply states this:

    if the clicked element (aka event.target -- see #4)
    is this (aka .box -- see #3), then...
    remove this

Note: This will exclude anything within .box that is clicked not just an <input>.

Demo

$('.box').click(function(event) {
  if (this === event.target) {
    $(this).remove();
  }
});
<fieldset class='box' style="width:500px;height:500px">
  <input type="text" style="width:100px;height:20px">
</fieldset>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370789

Only remove if the target of the event does not match input:

$('.thediv').click(function(e) {
  if (!e.target.matches('input')) {
    $(this).remove();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="thediv" style="width:500px;height:500px">
  other div content
  <input style="width:100px;height:20px">
</div>

Upvotes: 4

Abdelrahman Gobarah
Abdelrahman Gobarah

Reputation: 1589

on input click use .stopPropagation() this will prevent from call the parent click

$('.thediv').click(function(){$(this).remove()});

$('#input').click(function(e) {
  e.stopPropagation();
});
<div class="thediv" style="">
  <input type="input" id="input" /><br />
  text here 
  <h1>text here </h1>
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions