I have problem with a jQuery dropdown menu. My code:
$('.item-active, .item').click(function() {
$(this).toggleClass('item-active');
if($('h3').hasClass('item-active')) {
$(this).siblings().css( 'display', 'block' );
}
$(this).toggleClass('item');
if($('h3').hasClass('item')) {
$(this).siblings().css( 'display', 'none' );
}
});
<div>
<h3 class="item-active">item 1</h3>
<div class="item-desc">Lorem Lorem</div>
</div>
<div>
<h3 class="item">item 2</h3>
<div class="item-desc">Lorem Lorem</div>
</div>
<div>
<h3 class="item">item 3</h3>
<div class="item-desc">Lorem Lorem</div>
</div>
All I need is to have the menu toggle when the related h3 is clicked. Also, only one item may be active at the same time (the rest of the descriptions should be hidden)
To solve this you can simply use removeClass() to remove the .item-active class from all elements before toggling it on the the one which was clicked.
Also note that you can simplify the JS code to just amending the class and leave CSS to hiding/showing the .item-desc by using the + sibling operator. Try this:
$('.item').click(function() {
$('.item').not(this).removeClass('item-active');
$(this).toggleClass('item-active');
});
.item-active {
color: #C00;
}
.item-desc {
display: none;
}
.item-active + .item-desc {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3 class="item item-active">item 1</h3>
<div class="item-desc">Lorem Lorem</div>
</div>
<div>
<h3 class="item">item 2</h3>
<div class="item-desc">Lorem Lorem</div>
</div>
<div>
<h3 class="item">item 3</h3>
<div class="item-desc">Lorem Lorem</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With