emma
emma

Reputation: 759

How to use jquery toggle for multiple childs in different parents?

Basically i have a few parents that have the same class:

<div class="parent">
    <div class="child"></div>
</div>
<div class="parent">
    <div class="child"></div>
</div>
<div class="parent">
    <div class="child"></div>
</div>

And when i click on a parent class i want to toggle its child. For that i'm using:

$(document).ready(function(){
    $('.parent').click(function(e){
        $(this).children('.child').toggle();
    });
});  

This does toggle my child but if i leave it visible and i click on the next parent i want to make all other children disappear.

Is this possible using only jquery/javascript? Thank you!

Upvotes: 1

Views: 405

Answers (3)

Mohammad
Mohammad

Reputation: 21489

I think you need to show only one of childs. To do this work first hide all childs then show clicked child.

$('.parent').click(function(e){
  $(this).siblings().children('.child:visible').toggle();  
  $(this).children('.child').toggle();     
}).children(".child").toggle();

$('.parent').click(function(e){
  $(this).siblings().children('.child:visible').slideUp();  
  $(this).children('.child').slideDown();     
}).children(".child").slideUp();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">parent1
    <div class="child">child1</div>
</div>
<div class="parent">parent2
    <div class="child">child2</div>
</div>
<div class="parent">parent3
    <div class="child">child3</div>
</div>

Upvotes: 2

charlietfl
charlietfl

Reputation: 171679

You could use a class to manage display and just toggle that class on current parent and remove it from others

$('.parent').click(function(){
  $('.active').not(this).removeClass('active');
  $(this).toggleClass('active');
})
.parent{ margin-bottom:2em}
.child{display:none}
.active .child{ display:block}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">Parent 1
    <div class="child">Child</div>
</div>
<div class="parent">Parent 2
    <div class="child">Child</div>
</div>
<div class="parent">Parent 3
    <div class="child">Child</div>
</div>

Upvotes: 3

iPraxa Inc
iPraxa Inc

Reputation: 556

Please Try This:-

$('.parent').click(function(e){
            if($(this).children('.child').is(':visible')){
                $(this).children('.child').slideUp();
            }else{
                $('.parent .child').slideUp();
                $(this).children('.child').slideDown(); 
            }           
        });

Upvotes: 0

Related Questions