I want a window to close only when pop_up
is clicked (as opposed to clicking div contents). E.g. clicking the background layer hides the div. In the code below I don't want it to close #pop_up
when clicking the div contents bot only on "pop_up".
How can I do this?
$("#pop_up").click(function() {
$("#pop_up").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pop_up">
<div id="pop_up_content">
<h1> world </h1>
</div>
</div>
What you are experiencing is the bubbling and capturing behaviour of events. Check this answer What is event bubbling and capturing? .
The simples approach would be to attach a onClick to the child and stop the bubbling.
$("#pop_up_content").click(function(ev) {
ev.preventDefault()
ev.stopImmediatePropagation() // best to use to stop other event listeners from being called
});
You can use the event
argument of the click, and see if the click is inside another element (or it is the element itself)
JSFiddle: https://jsfiddle.net/32mz2x3x/1/
$("#pop_up").click(function(event) {
if ($(event.target).parents().andSelf().is('#pop_up_content')) {
return
}
$("#pop_up").hide();
});
I have used parents
to check if where you click is inside pop_up_content
element, and I used andSelf
because maybe you click on #pop_up_content
(and not inside it)
More info:
andSelf
functionis
functionparents
functionevent
objectIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With