views:

335

answers:

2

Similar to what Facebook does on its newsfeed, I want to allow commenting on numerous feed items, which I'm pulling via a php foreach statement. This is creating identical classes. So when I click .show_comments it activates everything.

I went through SO and found something akin to what you see below...but it's not working for me.

How do I target individual .show_comments to animate and toggle the selected item?

$j(function() {
    $j(this).find('.show_comments').click(function(){
     $j(this).find('.comments').slideDown("fast");
     $j(this).find(".answer_comments").toggle();
    });

    $j(this).find('.hide_comments').click(function(){
     $j(this).find('.comments').slideUp("fast");
     $j(this).find(".answer_comments").toggle();
    }); 
});
A: 

#show_comments is an id and ids need to be unique. when you generate the names/ sections, use something like

id='show_comments1'

and

id='answer_comments1'

to uniquely identify both sections

OR, traverse up the tree from element raising the event to a known parent and then find the answer child and toggle() it

Jonathan Fingland
sorry about that, i had them as classes.
Jung
+6  A: 

IDs should be unique in a HTML document. If you have several elements with id="show_comments" you are doing it wrong and you won't be able to access more than 1 of them through Javascript. The proper way of grouping elements is by classes.

The right way of doing it would then be something like this, assuming the HTML looks like the following:

<div id="item-1">
....text of whatever people are commenting on....
  <a href='#' class='toggle_comments'>show comments</a>
  <div class='comments' style='display: none;'>
  ... comments ...
  </div>
</div>

<div id="item-2">
....text of whatever people are commenting on....
  <a href='#' class='toggle_comments'>show comments</a>
  <div class='comments' style='display: none;'>
  ... comments ...
  </div>
</div>

And the Javascript/jQuery would then be:

$('a.toggle_comments').toggle(function() {
    $(this).next('div.comments').slideDown('fast');
    $(this).text('hide comments');
}, function() {
    $(this).next('div.comments').slideUp('fast');
    $(this).text('show comments');
});

And here is a demo of it in action.

Paolo Bergantino
+1 this is really the better way to do it
Jonathan Fingland
+1 very, very neat.
karim79