LoginSignup
1
0

More than 1 year has passed since last update.

[Rails]もっと見るボタンの実装(JavaScriptのみ、jQueryなし)

Posted at

完成イメージ

スクリーンショット 2021-08-20 10.48.50.png

合計のレコード数が9件だった場合、

最初は、6件だけ表示。
これを押すと、残りの3件が表示されるという仕組みを作る。

前提

マークアップコードはHamlで実装。

// Haml側でのデータの扱い
- @sections = 複数のセクション
- section: アプリケーション内で表示する後述の「contents」を格納するセクション
- contents: 「section」と1対多の関連がある、アプリケーション内で表示する複数のレコード

JS側

:javascript
  // もっと見る表示
  function SeeMore(contentsId, minimumContentsId, button) {
    const contents = document.getElementById(contentsId);
    const minimumContents = document.getElementById(minimumContentsId);
    const seeMoreButton = document.getElementById(button);

    minimumContents.style.display = "none";
    seeMoreButton.style.display = "none";

    if(contents.style.display == "flex") {
      contents.style.display = "none";
    } else {
      contents.style.display = "flex";
    }
  }

引数の説明

「contentsId」には、「全件表示」が格納されているidが入る。
「minimumContentsId」には、「制限表示」が格納されているidが入る。
「button」には、「もっと見るボタン」のidが入る(押下時にボタンも非表示にするため)

Haml

// section内の初期表示は6件にする
- content_max_display_count = 6

  - @sections.each do |section|
    .section_contents{id: "d#{section.id}" style: "display: none;"}
      - section.contents.limit(6).each do |content|
        // ここに制限表示の内容が入る
    .section_cotnents{id: "p#{sectioon.id}"}
      - section.contents.each do |content|
        // ここに全件表示の内容が入る

      // もっと見るボタン
      = link_to "もっと見る (他#{section.contents.count - content_max_display_count}件)", "#", remote: true, onclick: "SeeMore('p#{section.id}', 'd#{section.id}', 'see-more-button#{section.id}')"

link_toの第4引数、ここが肝。

onclick: "SeeMore('p#{section.id}', 'd#{section.id}', 'see-more-button#{section.id}')"

onclick時に、js側で設定したSeeMore()を発動する。
この際にSeeMore()に引数の設定を忘れずに行う。

まとめ

JSすごい。

1
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
1
0