Show/hide each element within a toggle class (jquery)

Asked

Viewed 5,265 times

3

I have a class .menu-departamento and inside of it I have a h3 and a ul li,in which I am putting an effect toogle.

In the code below when I click on a h3 displays all the ul and the desired is that it display only the ul that is just below h3 clicked.

Follow the example below:

<div class="menu-departamento">
    <h3>
        cartuchos e toners  
    </h3>
    <ul>
        <li>01</li>
        <li>02</li>
        <li>03</li>
        <li>04</li>
        <li>05</li>
    </ul>

    <h3>impressoras</h3>
    <ul>
        <li>01</li>
        <li>02</li>
        <li>03</li>
        <li>04</li>
        <li>05</li>
    </ul>

    <h3>Cadernos</h3>

    <ul>
        <li>01</li>
        <li>02</li>
        <li>03</li>
        <li>04</li>
        <li>05</li>
    </ul>

    <h3>acessórios</h3>
    <ul>
        <li>01</li>
        <li>02</li>
        <li>03</li>
        <li>04</li>
        <li>05</li>
    </ul>
</div>

<script>
$(document).ready(function(){
    $('.menu-departamento > ul > li').hide();

    $('.menu-departamento h3').click(function() {
        $('.menu-departamento > ul > li').toggle('slow, 1000');
    });

});
</script>

Example reference in jsfiddle: http://jsfiddle.net/scofieldm1/Lcbdpcju/

2 answers

4


You can use the function next() for this, which selects the next element.

In your example I modified the line $('.menu-departamento > ul > li').hide(); to hide all ul. Then the next() always select the next ul, since in your code there is always a ul after a h3.

$(document).ready(function() {
  $('.menu-departamento > ul').hide();
  
  $('.menu-departamento h3').click(function() {
    $(this).next().toggle('slow, 1000');
  });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="menu-departamento">
  <h3>cartuchos e toners</h3>
  <ul>
    <li>01</li>
    <li>02</li>
    <li>03</li>
    <li>04</li>
    <li>05</li>
  </ul>
  <h3>impressoras</h3>
  <ul>
    <li>01</li>
    <li>02</li>
    <li>03</li>
    <li>04</li>
    <li>05</li>
  </ul>
  <h3>Cadernos</h3>
  <ul>
    <li>01</li>
    <li>02</li>
    <li>03</li>
    <li>04</li>
    <li>05</li>
  </ul>
  <h3>acessórios</h3>
  <ul>
    <li>01</li>
    <li>02</li>
    <li>03</li>
    <li>04</li>
    <li>05</li>
  </ul>
</div>

  • Thanks, for the answer, I marked your question as right was basically what I needed.

3

Use a container between each listing. See how it looked on Jsfiddle.

Browser other questions tagged

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