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

【JS】メッセージをランダムで表示する

Posted at

概要

この記事では、メッセージのランダム表示について、実装方法をまとめる。

デモはこちら🔽

See the Pen Random Message by Hatsumi Shimizu (@Hatsumi-Shimizu) on CodePen.

仕様

  • 「次のメッセージ」ボタンを押すと、メッセージがランダムで表示される
  • 直前のメッセージとは異なるメッセージが表示される

実装

DOM要素取得後、下記の処理を追加した。

// 現在表示中のメッセージ番号
let currentIndex = 0;

nextBtn.addEventListener('click', () => {
  card.classList.add('flip');

  setTimeout(() => {
    let newIndex;
    
    // 前回と異なるメッセージが選ばれるまで繰り返す
    do {
      newIndex = Math.floor(Math.random() * messages.length);
    } while (newIndex === currentIndex);
    
    currentIndex = newIndex;
    messageElement.textContent = messages[currentIndex];
  }, 300);

  setTimeout(() => {
    card.classList.remove('flip');
  }, 600);
});

ポイントは下記の3つ🔽

  • 変数currentIndexで現在表示されているメッセージのインデックス番号を管理
  • 変数newIndexで次に表示されるメッセージのインデックス番号を管理
    • Math.random()を用いた乱数の生成により、インデックス番号を取得
  • currentIndexnewIndexが一致しなければ、異なるメッセージであるとみなす

まとめ

メッセージのランダム表示についてまとめた。

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?