Closing jquery on parent click

I want the window to close only when clicked pop_up(as opposed to clicking on the contents of a div). For instance. clicking on the background layer hides the div. In the code below, I do not want it to close the #pop_updiv on β€œpop_up” only when the bot is clicked.

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>
Run codeHide result
+6
source share
4 answers

You can use the eventclick argument and see if the click is inside another element (or 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();
});

parents , pop_up_content, andSelf, , , #pop_up_content ( )


:

+3

, , - . ?.

onClick .

$("#pop_up_content").click(function(ev) {
   ev.preventDefault()
   ev.stopImmediatePropagation() // best to use to stop other event listeners from being called
});
+6

, :not():

$("#pop_up").on('click', ':not(#pop_up_content)', function (e) {
    $("#pop_up").hide();
});
+2

JSBin: http://jsbin.com/hoyizos/edit?html,css,js,output

$("#pop_up").click(function(e) { 
    if ($(event.target).is($("#pop_up"))){   
        $("#pop_up").hide();  
    }     
});
h1{
  margin:50px 50px;
  background-color:red;
  display:inline;
}

#pop_up_content{
  background-color:yellow;
}

#pop_up{
  margin:10px;

  background-color:green;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-3.0.0.js"></script>
</head>
<body>
<div id="pop_up">
            <div id="pop_up_content">pop_up_content
                <h1> world </h1>
            </div>
I am the pop_up!
 </div>
</body>
</html>
Hide result

bubbling!: , , .

Do not use andSelf()if you plan to use jQuery 3.x because it has been deprecated since v1.8 and will be removed in jQuery v3 .

Note. This function is deprecated and is now an alias for .addBack (), which should be used with jQuery 1.8 and later.

If you are using jQuery 1.8 <Use instead addBack.

+1
source

Source: https://habr.com/ru/post/1014090/


All Articles