I start by saying that I had a missing% in my sample structure.
As for the problem itself, it is easier to solve by doing "
and slideUp
manually. When you click on an element it makes slideDown
to all, which will only affect the one that is down and slideUp
to which it was clicked.
Example:
$(".botão").on("click", function(){
$(".sub-item").slideUp();
$(this).next().slideDown();
});
.sub-item {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="menu-item">
<div class="botão">item 1</div>
<div class="sub-item">subitem1</div>
</div>
<div class="menu-item">
<div class="botão">item 2</div>
<div class="sub-item">subitem2</div>
</div>
<div class="menu-item">
<div class="botão">item 3</div>
<div class="sub-item">subitem3</div>
</div>
If you use
slideDown
instead of
slideToggle
it will have exactly the same effect, but it turns out to be more confusing because it will only always open and never close, so it always always corresponds to
slideDown
.
As already mentioned in comments it is not a good idea to reinvent the wheel and what you are trying to build already exists and is called a chord. JQuery UI already has this in its plugins already contemplating several possible configurations like:
- Custom Icons
- Collapsible menus
- No automatic size
- Authoritative
JQuery UI Accordion Reference