Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery closing on parent click

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>
like image 603
Tomislav Tomi Nikolic Avatar asked Jan 14 '17 20:01

Tomislav Tomi Nikolic


2 Answers

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
});
like image 180
FabioCosta Avatar answered Sep 21 '22 04:09

FabioCosta


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:

  • jQuery andSelf function
  • jQuery is function
  • jQuery parents function
  • jQuery event object
like image 28
Aminadav Glickshtein Avatar answered Sep 23 '22 04:09

Aminadav Glickshtein