Search code examples
jqueryparentshow-hidechildren

How to open and close the same div in JQuery


Hey guys how can I close a div which is opend with show(). For Example: I have a "div a" which includes a "div b" which is hidden at first and when I click on "div a" the "div b" (children) should show up. When I click on an [x] inside the "div b" exactly this div should close.

In my minimal example of this I already find out how to open the right div which is the children of the parent div. But how can I close the parent again? In my example I only can close the "hide Button" but not the whole div "Tag-Cloud". I also tried to implement the parent() function and the parentUntil() function but it failed.

Can you guys help me?

$(document).ready(function() {

  $(".film").click(function() {
    $(this).children(".tag-cloud").show(function() {
      $(".fa-close").click(function() {
        $(this).parent().hide();
      });
    });
  });

});
.tag-cloud {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="film">

  <h4 class="film-title">Open the div here</h4>

  <div class="tag-cloud">
    <!-- tag-cloud -->
    <i class="fa fa-2x fa-close"></i>
    <ul>
      <li><a href="">tag1</a></li>
      <li><a href="">tag2</a></li>
    </ul>
    <div class="exit-tags">
      <i class="fa fa-2x fa-close">[Close Button]</i>
      <!-- The close button for the tag-cloud -->
    </div>
  </div>

</div>


Solution

  • 3 things to mention

    1. use on('click'.. function it will make your life easyer
    2. both clicks are just clicks so no reason to put one inside the other
    3. event.stopPropagation() is the most important thing here. Cause if you click inside the div to close it you also click on the div itself. with stop propagation you stop the event from bubbeling up the DOM because if not you hide() and then you show() again.

    More about event.stopPropagation() can be found here

    $(document).ready(function(){
    
      $(".film").on('click', function (){
        $(this).children(".tag-cloud").show();
      });
    
      $(".fa-close").on('click', function (event){
        event.stopPropagation();  // do not forget this
        $(this).closest(".tag-cloud").hide();
      });
    
    });
    .tag-cloud {
    	display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="film">
    
      <h4 class="film-title">Open the div here</h4>	
    
      <div class="tag-cloud"><!-- tag-cloud -->
        <i class="fa fa-2x fa-close"></i>
        <ul>
          <li><a href="">tag1</a></li>
          <li><a href="">tag2</a></li>
        </ul>
        <div class="exit-tags">
          <i class="fa fa-2x fa-close">[Close Button]</i><!-- The close button for the tag-cloud -->
        </div>
      </div>
    
    </div>