Iterating through array in Rails as separate jQuery objects

Home / Uncategorized / Iterating through array in Rails as separate jQuery objects

Question:
I am iterating through an array in Rails to show a set of articles. I’d like a button to slide Toggle the article open when clicked (so each would be a headline and button, and the text would be revealed on button click).

The array looks like:<% @articles.each do |article| %>

<%= article.title %>

<%= markdown article.content %>

<% end %>

I am then trying to toggle the article_content with the following:

After reading some other questions, I believe the issue is that article_content is a class, which is why currently the button opens and collapses all of the content text.

If I am iterating through an array, can I assign different IDs to target as my object so clicking the button for Article 1 opens and closes Article 1 only?


Answer:
Unless you have a specific reason to assign the id to the button, then set a class on the button and then you can use .next() to achieve what you want.

jquery:$(".clickme").click(function() {
$(this).next(".article_content").slideToggle("300", function() {});
});

Html: change id="clickme" to class="clickme"

This will allow you to toggle multiple elements the way you want.

Demo below

$(".article_content").hide()
$(".clickme").click(function() {
$(this).next(".article_content").slideToggle("300", function() {});
});

article 1

content 1

article 2

content 2

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *