0

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?

Abdelrahman Gobarah
  • 1,544
  • 2
  • 12
  • 29
AGamePlayer
  • 7,404
  • 19
  • 62
  • 119
  • 1
    read about `event.stopPropagation()` [here](https://stackoverflow.com/questions/5963669/whats-the-difference-between-event-stoppropagation-and-event-preventdefault) – Muhammad Usman Feb 03 '20 at 05:26

3 Answers3

4

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>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

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>
Abdelrahman Gobarah
  • 1,544
  • 2
  • 12
  • 29
1

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>
Community
  • 1
  • 1
zer00ne
  • 41,936
  • 6
  • 41
  • 68