LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】each文内の要素をjQueryでシャッフル表示させる方法

Posted at

何がしたい?

each文で回した親要素に含まれる子要素の順番をランダムにシャッフルさせて表示させたい。

shuffle_card.jpg

方法

viewファイル

<% # each文の周回をiとする(iの初期値は0) %>
<% @cards.each_with_index do |card, i| %>
  <div class="container">
    <% # item_wrapperにRuby構文でインデックスを付与する %>
    <div class="row item_wrapper_<%= i+1 %>">
      <div class="card"><%= card.content_a %></div>
      <div class="card"><%= card.content_b %></div>
      <div class="card"><%= card.content_c %></div>
    </div>
  </div>
<% end %>

jQuery

function shuffleContent(container) {
  var content = container.find(".card");
  var total = content.length;
  content.each(function() {
    content.eq(Math.floor(Math.random() * total)).prependTo(container);
  });
}
$(function() {
  for (var i=1; i<1000; i++) {
    shuffleContent($(".item_wrapper_" + i)); // + を使って文字列と変数をつなげる
  }
});

解説

Viewファイル
item_wrapper_<%= i+1 %>iはeach文のインデックス値が代入されるので、item_wrapper_1, item_wrapper_2, item_wrapper_3,,,という親要素が生成されます。

jQuery
.item_wrapper_" + i要素に対してJSのコードが適用されます。
このiはfor文により、1から999まで回ります。
Railsが生成したHTML上のitem_wrapper_1, item_wrapper_2, item_wrapper_3,,,の親要素それぞれのなかから.card要素を見つけ出し、それを都度シャッフルさせます。

これにより、.card要素をシャッフル表示させることができます。

参考

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