Reputation: 7736
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
Reputation: 43910
In the following demo:
.box
is the parent element that listens for the click event..box
is also referred to as event.currentTarget
because it is registered to the click event..box
is also considered this
within the callback function.event.target
is the origin of the event -- the element that the user clicked..box
has an <input>
child element.if the clicked element (aka
event.target
-- see #4)
isthis
(aka.box
-- see #3), then...
removethis
Note: This will exclude anything within .box
that is clicked not just an <input>
.
$('.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
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
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