josh reilly
josh reilly

Reputation: 53

JQuery Toggle next class

I am making a blogging website and want to have headers or links show the post when clicked, I have it working so they all open when one is clicked but I just want it to be the one below the header

JQuery :

$(document).ready(function(){

    $('.slidingDiv').hide();
    $('.show_hide').show();

    $('.show_hide').click(function(){
        $('.slidingDiv').slideToggle();
    });

});

PHP :

for($i=0; $i<5; $i++)
{
    print "
      <a href='#' class='show_hide'>Article name</a>
      <div class='slidingDiv'>
          Fill this space with really interesting content. 
      </div>
      <br>
      <br>
    ";
}

Thanks in advance

Upvotes: 2

Views: 1928

Answers (2)

cl3m
cl3m

Reputation: 2801

You should find the next .slidingDiv element:

$(document).ready(function(){

    $('.slidingDiv').hide();
    $('.show_hide').show();

    $('.show_hide').click(function() {
        // 'this' is now the clicked .show_hide element
        $(this).next().slideToggle();
    });

});

Upvotes: -1

Andrew Brooke
Andrew Brooke

Reputation: 12173

You can use .next to select only the next .slidingDiv

$(this).next('.slidingDiv').slideToggle();

Snippet

$('.slidingDiv').hide();
$('.show_hide').show();

$('.show_hide').click(function() {
  $(this).next('.slidingDiv').slideToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='show_hide'>Article name</a>
<div class='slidingDiv'>
  Fill this space with really interesting content.
</div>
<br>
<br>
<a href='#' class='show_hide'>Article name</a>
<div class='slidingDiv'>
  Fill this space with really interesting content.
</div>

Upvotes: 4

Related Questions