views:

39

answers:

2

i have multiple divs with the same class on my page. I want to be able to toggle them individually. Using this script:

 $(document).ready(function() {
   $('.file').hide();

   $('a.toggle').click(function() {
      $('.file').slideToggle(1000);
      $(this).text($(this).text() == 'show' ? 'hide' : 'show');
      return false;
   });
 });

the HTML looks like this:

<div class="file-wrapper">
 <h5>(<a href="#" class="toggle">show</a>)</h5>
  <div class="file">
   <?php require "lipsum.php"; ?>
  </div><!-- .file -->
</div><!-- .file-wrapper -->

<div class="file-wrapper">
 <h5>(<a href="#" class="toggle">show</a>)</h5>
  <div class="file">
   <?php require "lipsum.php"; ?>
  </div><!-- .file -->
</div><!-- .file-wrapper -->

Now if i click either of the links it will toggle both divs on the page (the page will ultimately have up to 10 toggleable divs. I know i could just add IDs to each div, but i don't want to have to write the jquery script once for each id.

I'm fairly new to jquery so I'm sure there is a simple way to do this. I've tried using .closest('div') but that isn't working either.

Any help?

+2  A: 

Maybe you could try with this:

$(this).parent('h5').next('div.file').slideToggle(1000);

Edit: Here's an example: http://jsfiddle.net/6GRJr/

robertbasic
yes yes thank you so much
thomas
A: 

this is because it's always hiding all your divs with class file do it like this

$(document).ready(function() {
   $('.file').hide();

   $('a.toggle').click(function() {
      $('div.file', this.parentNode).slideToggle(1000);
      $(this).text($(this).text() == 'show' ? 'hide' : 'show');
      return false;
   });
 });
TriLLi
You would need to to add one more `.parentNode` on there since `div.file` will only be matched against descendants and it is a sibling of `this.parentNode`. `$('div.file', this.parentNode.parentNode)`
patrick dw