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!
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>
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>
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();
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.