LoginSignup
2
0

More than 1 year has passed since last update.

[Rails]もっと見るボタンで全文を表示させる

Posted at

はじめに

自作のRailsアプリケーションでもっと見るボタンを実装したのでメモ。以下のようなイメージで投稿した記事を最初に折りたたんだ状態で「もっと見る」ボタンを押すと全文を表示させるというものです。

スクリーンショット 2021-06-09 18.48.26.png

スクリーンショット 2021-06-09 18.48.37.png

実装方法

※筆者はindexページで実装しています。
また今回はJQueryでAjaxを使わずに行います。

まず手を加える前のコードは以下のようになっています。

index.html.erb
<% @posts.each do |post| %>
   <%= post.body%>
<% end %>

今回は200文字以上の場合にもっと見るボタンを付け足すと想定します。

index.html.erb
<div class="content-body">
  <% @posts.each do |post| %>
    <%if post.body.length > 200 %>
      <p><%= post.body.truncate(200)%></p>
      <p>&lt;もっと見る&gt;</p>
    <%else%>
      <p><%= post.body %></p>
    <%end%>
  <% end %>
</div>

上記のようにif文で200文字以上の時は文字をtruncateで省略し200文字未満の場合はそのまま表示します

次にJQueryを使うための追記をします。
以下のように追記をします。

<div class="content-body">
  <% @posts.each do |post| %>
    <%if post.body.length > 200 %>
      <!--追記-->
      <div class="truncated">
        <p><%= post.body.truncate(200)%></p>

        <!--class="see-more"を追記-->
        <p class="see-more">&lt;もっと見る&gt;</p>
      </div>

      <!-- 追記 style= "display: noneで 通常時は見えなくする-->
      <div class="untruncated" style="display: none">
        <p><%= post.body %></p>
      </div>
    <% else %>
      <p><%= post.body %></p>
    <% end %>
  <% end %>
</div>

追記した部分はコメントを追加しています。

最後にjsを設定します

jsファイル
$('.see-more').click(function(){
  $(this).closest(".content-body").find(".truncated").hide();
  $(this).closest(".content-body").find(".untruncated").show();
})

以上を設定すると実装完了です。
説明するとsee-moreをクリックした時に(1行目)その1番近い親要素であるcontent-bodyの中のtruncatedを隠す(2行目)。そのあとcontent-bodyの中のuntruncatedを表示させる(3行目)

以上になります。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0