Open and close div with jQuery slideToggle feature

Asked

Viewed 960 times

2

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 boot class, the div sub-item opens with no slideToggle from jquery, I would like as I click on another div with boot class to open div sub-item, close.

I’ve used sibling() and it didn’t work

Could someone help me? Thank you

  • 1

    What you’re looking for wouldn’t be the Accordion? Example in Jquery UI

  • 1

    closes all by the class before opening the new

  • I didn’t get Wess?

  • Yes Victor, it’s almost an accordion, but I can’t use jquery ui

  • "...I can’t use jquery ui"...ta by writing the framework itself? There’s a good people here on the page that has the framework itself. If successful and send a version when ready.

1 answer

1

I start by saying I had some " missing in its example structure.

As for the problem itself it is easier to solve by doing slideUp and slideDown manually. When you click on a widget slideUp to all, which will only affect the one who is down and does slideDown to which 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>
<div class="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 slideToggle instead of slideDown will have exactly the same effect, but it may end up being more confusing because it will just always open and never close, so it always corresponds only to slideDown.


As has already been said in comments it is not fitting to reinvent the wheel and what you are trying to build already exists and is called an agreement. Jquery UI already actually has this in their plugins already contemplating several possible configurations like:

  • Custom icons
  • Collapsible menus
  • No automatic size
  • Milkable

Reference for Jquery UI Accordion

  • Isac, I don’t want to reinvent the wheel, simply by decision of a superior I can’t use jQuery UI

Browser other questions tagged

You are not signed in. Login or sign up in order to post.