Open and close div with jQuery slideToggle feature

0

I have the following structure:

<div class="menu-item">
  <div class="botão"></div>
  <div class="sub-item></div>
</div>
<div class="menu-item">
  <div class="botão"></div>
  <div class="sub-item></div>
</div>
<div class="menu-item">
  <div class="botão"></div>
  <div class="sub-item></div>
</div>
When I click on the div with the class button, the div sub-item opens with jQuery slideToggle's refuse, I would like it as I clicked on another div with a class button to open the sub-item div that was open, / p>

I've already used sibling () and it did not work

Can anyone help me? Thanks

    
asked by anonymous 07.05.2018 / 22:17

1 answer

0

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

    
07.05.2018 / 23:36