There is a parent unit and he has 1 child

<div id="pop_bg"> <div id="pop_content"> </div> </div> 

It is a click event on the parent, if I click on pop_bg closes, but the trouble is that when I click on the child’s content ( pop_content ), I’ll click on pop_bg , and pop_bg closes, why? How to fix?

  • writing code correctly - Serge Esmanovich
  • 6
    add the javascript you are using, but you probably need the stopPropagation method - Grundy
  • I learn to write correctly, so I ask how is better - user197892

3 answers 3

Try this with stopPropagation();

 $('body').on('click', '#open', function(e) { e.preventDefault(); $("#pop_bg").show(); }); $('body').on('click', '#pop_bg', function(e) { e.preventDefault(); $("#pop_bg").hide(); }); $('body').on('click', '#pop_content', function(e) { e.stopPropagation() }); 
 #pop_bg { background: rgba(0, 0, 0, 0.5); position: fixed; padding: 50px; z-index: 1000; top: 0; right: 0; bottom: 0; left: 0; display: none; overflow-x: hidden; overflow-y: overlay; } #pop_content { width: 500px; height: 100px; margin: auto; background: #FFF; box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a id="open">Open modal</a> <div id="pop_bg"> <div id="pop_content"> Content </div> </div> 

    as an option, you can write this:

     /*HTML*/ <div id="pop_bg"> <div id="pop_content"> </div> </div> /*CSS*/ #pop_bg { width:350px; height:350px; background-color:#ccc; position:relative; } #pop_content { position:absolute; width:80%; height:80%; background-color:red; margin:auto; top:0; bottom:0; left:0; right:0; } /*JS+JQUERY*/ $('#pop_bg').bind('click', function(e) { if (e.target.id != 'pop_bg') return false; $(this).hide(); }); 

    http://codepen.io/anon/pen/NxdOoO

      Version without jQuery:

       document.querySelector('#pop_bg').addEventListener('click', function(e) { if (this === e.target) { // Ваш код } });