0

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| %>
  <div class="article_header">
    <h1><%= article.title %></h1>
    <button id="clickme" type="button">Show More!</button>
 <div class="article_content">    
          <p><%= markdown article.content %></p>
   </div>
      <% end %>
</div>

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

<script>
$( ".article_content" ).hide()
$( "#clickme" ).click(function() {
  $( ".article_content" ).slideToggle( "300", function() {
  });
});
</script>

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?

2 Answers 2

1

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() {});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="article_header">
  <h1>
    article 1
  </h1>
  <button class="clickme" type="button">Show More!</button>
  <div class="article_content">
    <p>
      content 1
    </p>
  </div>
</div>

<div class="article_header">
  <h1>
    article 2
  </h1>
  <button class="clickme" type="button">Show More!</button>
  <div class="article_content">
    <p>
      content 2
    </p>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

@darkginger no problem, happy to help
1

Make the button selector also a class:

<button class="clickme" type="button">Show More!</button>

Then try to find the nearest article_content of that button. The jQuery portion would look something like this:

<script>
  $( ".article_content" ).hide()
  $( "button.clickme" ).click(function() {
    $(this).siblings( ".article_content" ).slideToggle( "300", function({});
  });
</script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.