Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Dave Faliskie
Dave Faliskie
17,793 Points

How to use the same button class to hide and display different content with multiple buttons

I am using Ruby on rails to make a forum like page. I have it set up so that there is an original post, and users can 'respond' on that post. Then a user can also comment on the response. I do not want to display all the comments on the responses unless the user clicks a button "view all comments"

As of now I have it set up so the comments (wrapped in the div called .comments) are hidden, then the button (class of .comment_button) is clicked and the comments appear.

jQuery ->
    $('.comments').hide()
    $('.comment_button').on 'click', (event) ->
        $('.comments').toggle()

The problem is that there are many 'responses' and when the button is clicked to view the comments on one response, it displays the comments under every response. I want it so that if you click the button only the comments are displayed for the response you clicked the button for.

I hope I explained this problem well enough. Any help would be awesome!

1 Answer

Hugo Paz
Hugo Paz
15,622 Points

Hi Dave,

If you have the toggle button inside the comments div you can try to traverse it with .parent()

Something like this

$('.comment_button').on 'click', (event) ->
        $(this).parent().toggle()

I dont know the syntax in Ruby but i believe you get the idea. $(this) refers to the button being pressed, .parent gets the parent of the button which is now selected and then the toggle hides or displays it.

If the button is a sibling, there are other methods of traversing the dom but you get the gist of it.