1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[jquery]いっぱいある要素を並び順・表示ともにランダムに出力する

Posted at
<ul class="js-feature-ramdom">
  <li><a href="link"><img src="img1.jpg" alt="img1"></a></li>
  <li><a href="link"><img src="img2.jpg" alt="img2"></a></li>
  <li><a href="link"><img src="img3.jpg" alt="img3"></a></li>
  <li><a href="link"><img src="img4.jpg" alt="img4"></a></li>
  <li><a href="link"><img src="img5.jpg" alt="img5"></a></li>
  <li><a href="link"><img src="img6.jpg" alt="img6"></a></li>
</ul>

<script>
$(function() {
  let wW = $(window).width();
  let arr = [];

  $(".js-feature-random li").each(function() {
    arr.push($(this).html());
  });

  $(".js-feature-random").empty();

  arr.sort(function() {
    return Math.random() - Math.random();
  });

  if(wW > 640) {//PCの時は3つ
    for(i=0; i < 3; i++) {
        $(".js-feature-random").append('<li>' + arr[i] + '</li>');
    }
  } else {
    for(i=0; i < 4; i++) {//スマホの時は4つ
      $(".js-feature-random").append('<li>' + arr[i] + '</li>');
    }
  }
});
</script>
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?