Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery toggling all divs in an .each loop

I have my posts lopping on an .each loop and I have a link to display comments on the bottom of the loop.

I want to show the comment section on click, but when I click comments for all posts open as well. I only want the one that's clicked to open.

I've tried a ton of different examples I've found on this site, but so far none of them have worked.

I'm sure this is extremely easy to accomplish, but I'm a JavaScript noob.

Here is the JSFiddle link - http://jsfiddle.net/omgwhyamisobad/h0yhvqa3/

As well as the code snippet -

JS

$(document).ready(function() {
  $('.artist-micropost-comment-click').click(function() {
    $('.artist-micropost-comments-container').toggle();
  });
});

HTML

<div class="artist-micropost-social">
  <a class="artist-micropost-comment-click">comments</a>
</div>
<div class="artist-micropost-comments-container">
...
...
...
</div>

<div class="artist-micropost-social">
  <a class="artist-micropost-comment-click">comments</a>
</div>
<div class="artist-micropost-comments-container">
...
...
...
</div>

<div class="artist-micropost-social">
  <a class="artist-micropost-comment-click">comments</a>
</div>
<div class="artist-micropost-comments-container">
...
...
...
</div>

CSS

.artist-micropost-comments-container {
  display: none;
}
like image 504
Alex Heil Avatar asked Feb 11 '23 03:02

Alex Heil


1 Answers

The way that you are trying to grab the relevant element is wrong. You need to traverse the DOM with respect to the element that is being clicked. If you try to use the direct class selector in this case, then it would select all the elements which are having the supplied class.

Try,

$(document).ready(function() {
  $('.artist-micropost-comment-click').click(function() {
    $(this).closest('.artist-micropost-social')
             .next('.artist-micropost-comments-container').toggle();
  });
});

DEMO

like image 62
Rajaprabhu Aravindasamy Avatar answered Feb 13 '23 22:02

Rajaprabhu Aravindasamy