jqueryhtmlslidetoggle

slideToggle the next element


I want 5 <p> tags that when clicked, display a <div> that is underneath. I could do it where I name each <p> and each <div> different but that would lead to a lot of jQuery.

So, at the moment I have:

<p class="flip">Example</p>
<div class="panel">
  <p>Example Panel</p>
</div><!--End panel-->

<p class="flip">Example</p>
<div class="panel">
  <p>Example Panel</p>
</div><!--End panel-->

<p class="flip">Example</p>
<div class="panel">
  <p>Example Panel</p>
</div><!--End panel-->

The jQuery I have at the moment is:

$(document).ready(function() {
  $('.flip').click(function() {
    $('.panel').slideToggle('slow');
  });
});

Which obviously toggles all the .panels at once. To clarify, I want the first .flip to toggle the first .panel.


Solution

  • Just need to do some simple DOM traversal to select the correct <div class="panel"> element relative to the <p class="flip"> that was clicked on:

    $('.flip').click(function(e) {
        $(this).next('div.panel').slideToggle('slow');
    });
    

    Inside the click event handler function, this is the <p> element that was clicked on. Calling .next('div.panel') will select the next element in the DOM if it's a <div> and it has the class panel. If you need to skip any sibling elements, you can double up the .next() calls, like .next().next().