Jack
Jack

Reputation: 3

Is there a way to make this jquery script dynamic?

I'm using this jquery code to show and hide divs on my page. As you can see, I an limited to 5 divs. Is there a way to make them dynamic?

$(document).ready(function() {
  $('.box').hide();
  $('a.toggle').click(function() {
    $('.box').toggle(400);
    return false;
  });
});

<a href="#" class="toggle" title="Show Comments"><img src="images/read.gif" alt="" /></a>
<div class="box" class="comment">hidden content</div>

This is my revised code

$(function () {
  $('div.box').hide();
  $('a.toggle').click(function () {
    $(this).next('div.box').toggle(400);
  });
});

<div class="entry">
  <h3>Title</h3>
  <p>content</p>
  <p class="posted">Posted by Admin<br />
  <a href="#" class="toggle">
    <img src="read.gif" alt="" />
  </a>
</div>
<div class="box" class="comment">Hidden</div>

Upvotes: 0

Views: 86

Answers (1)

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827276

Looking at your markup, you could do something like this:

$(document).ready(function () {
  $('div.box').hide();

  $('a.toggle').click(function () { // all A elements with class 'toggle'
    $(this).next('div.box').toggle(400); // toggle the next DIV with class 'box'
  });
});

Basically bind a click handler to all your links with class toggle, and then when they are clicked, it will look for the next sibling (relative to the clicked link) that is a div with class box, using the Traversing/next function.

Check the above example with your markup here.

Edit: I reviewed your markup, and your .toggle links are nested inside a div.entry element, also there is an unclosed paragraph, so I've adjusted the code to your markup again:

$(function () { 
  $('div.box').hide(); 
  $('a.toggle').click(function () { 
    $(this).parents('.entry').next('div.box').toggle(400);
  }); 
});

You will notice that I look for the div.entry element, since the .box are siblings of them.

Check an update example here.

Upvotes: 3

Related Questions