I would like to use a simple link, like Facebook does, to toggle (unlike Facebook show AND hide) the comments of a post. However, being the list of posts in my application obtained by iteration, every post apparently can:
have comments enclosed in a div
that share with the comments of all the other posts the same id
or class
have comments enclosed in a div
element with unique id
or class
generated using (for instance) the id
of the post
In the first case, I cannot use the link and its id
or class
to toggle with jQuery only the comments belonging to one post: I would toggle the comments of all the posts. There might be a solution though: forget about the link and use the div
parent to the div
containing the comments to toggle it:
<div id="comments-parent">
<%= link_to "Show/hide comments", "#", id="comments-link" %>
<ol id="comments">
<% post.comments.each do |comment| %>
<li id="<% comment.id %>">
<span class="comment-content"><%= comment.content %></span>
</li>
<% end %>
</ol>
</div>
With jQuery I can do something like this:
$('#comments').hide();
$('#comments-parent').click(function() {
$(this).children('#comments').toggle();
});
This solution is horrible... Comments are toggled clicking on a very large area.
The second case, with a <ol id="comments-<%=post.id %>">
, could be the solution:
$('#comments-all').hide();
$('#comment-link').click(function() {
$('#comments-1').toggle();
});
However I would not know how to realize it, or if it is possible to realize it, that is how to pass to jQuery the information about "all ids
starting with comments-
" or above all about a particular id
.
You're pretty close to what I would have done. You can however bind it to the link like so:
$('.toggleLink').on('click', function() {
$(this).closest('.post').find('.comments').toggle();
});
Here is an example of what I think you want to do.
The reason why this works is due to using this
which is a context based variable in javascript. In this particular case, this
refers to the link element that triggered the click event. So from there we can access the correct surrounding elements for toggle