Phil Lockwood
Phil Lockwood

Reputation: 43

Expand/Collapse List of Items with jQuery

I have a list of blog posts on a page and need to give users the ability to expand/collapse details for each. I've looked around at options like next() but the structure of each blog post doesn't really allow for siblings.

<div class="post">
     <div class="controls">
          <ul>
               <li>Permalink</li>
               <li><a href="#" class="showcomments">Comments</a></li>
          </ul>
     </div>
     <div class="comments">Comments go here</div>
</div>

I have an unlimited number of these posts on a page, so I need a simple function that makes it so that if I click on the "Comments" link for any post, the .comments panel for only that post expands/collapses (clicking that link should toggle the corresponding comments div).

Upvotes: 0

Views: 2700

Answers (3)

Scott Mermelstein
Scott Mermelstein

Reputation: 15397

This might do the trick:

$(.showcomments).on("click", function() {
   $(this).parent().parent().find(".comments").show(); 
}

The idea is that it's setting an on-click callback, and inside, each element is finding its grandparent, and searching for the comments section, and showing it.

Upvotes: 0

adeneo
adeneo

Reputation: 318202

Target the link, toggle the sliding on the comments in that post, and slide all other comments up :

$('.showcomments').on('click', function(e) {
    e.preventDefault();
    var comment =  $(this).closest('.post').find('.comments');
    $('.comments').not(comment).slideUp();
    comment.slideToggle();
});

Upvotes: 1

Pete Scott
Pete Scott

Reputation: 1526

If the structure of the HTML cannot be modified, you're going to have to traverse the DOM... from the click event target (the anchor), up to its container (li) up to ITS container (ul) up to ITS container (div.controls) and then next() to find div.comments. jQuery can make that a pretty easy chain, but it is obviously somewhat fragile.

If you CAN modify the structure of the HTML, you have a slew of better options available to you, and can use IDs and data- attributes to avoid the overhead of traversing the DOM.

Upvotes: 1

Related Questions