🫠

#5 ボタンを配置して挙動をつける

に公開

#5 ボタンを配置して挙動をつける – タイマーを目で見えるように!

前回は JavaScript で簡単なタイマー機能を試作しました。
今回はそれを**「画面に表示」**し、3つのボタンの操作で動作が変化するようにします。


🧩 今回のポイント

  • 残り時間を「00:00」形式で画面に表示
  • Start / Stop / Reset を横並びに配置
  • ボタンのクリックで機能が反応する

🖥️ HTMLとCSSの更新

<!-- HTML本体 -->
<div class="timer-container">
  <div id="timer-display">00:00</div>
  <div class="button-group">
    <button id="start-btn">Start</button>
    <button id="stop-btn">Stop</button>
    <button id="reset-btn">Reset</button>
  </div>
</div>

<!-- CSS(画面中央に配置&ボタン横並び) -->
<style>
  .timer-container {
    text-align: center;
    margin-top: 80px;
    font-family: sans-serif;
  }

  #timer-display {
    font-size: 48px;
    margin-bottom: 20px;
    font-weight: bold;
  }

  .button-group {
    display: flex;
    justify-content: center;
    gap: 16px;
  }

  .button-group button {
    padding: 8px 20px;
    font-size: 16px;
    cursor: pointer;
  }
</style>

🔍 なぜこのレイアウトにしたのか?

CSSプロパティ / セレクタ 内容・使い方 理由・意図
text-align: center; テキストや要素を中央に配置 レイアウト全体の視認性を高め、タイマー表示に集中できるように
.button-group ボタン3つ(Start / Stop / Reset)を横並びに配置 操作系統が一か所にまとまることで直感的なUIに
gap: 16px; .button-group内のボタン同士の間隔を指定 間隔を適切にとることでボタンが密集せず、押し間違いを防ぐ
#timer-display フォントサイズ大きめ・太字に設定 タイマーとしての主機能を目立たせ、視認性を強化

🧪 JavaScriptを画面表示対応に変更

<script>
  const startBtn = document.getElementById("start-btn");
  const stopBtn = document.getElementById("stop-btn");
  const resetBtn = document.getElementById("reset-btn");
  const timerDisplay = document.getElementById("timer-display");

  let timer;
  let remainingTime = 0;
  let isRunning = false;

  function formatTime(seconds) {
    const min = String(Math.floor(seconds / 60)).padStart(2, '0');
    const sec = String(seconds % 60).padStart(2, '0');
    return `${min}:${sec}`;
  }

  function updateDisplay() {
    timerDisplay.textContent = formatTime(remainingTime);
  }

  function startTimer(duration) {
    clearInterval(timer);
    remainingTime = duration;
    isRunning = true;
    updateDisplay();

    timer = setInterval(() => {
      if (remainingTime <= 0) {
        clearInterval(timer);
        isRunning = false;
        alert("時間終了!");
        return;
      }
      remainingTime--;
      updateDisplay();
    }, 1000);
  }

  startBtn.addEventListener("click", () => {
    if (!isRunning) {
      const workMinutes = parseInt(document.querySelector("input:nth-of-type(1)").value) || 0;
      startTimer(workMinutes * 60);
    }
  });

  stopBtn.addEventListener("click", () => {
    clearInterval(timer);
    isRunning = false;
  });

  resetBtn.addEventListener("click", () => {
    clearInterval(timer);
    isRunning = false;
    remainingTime = 0;
    updateDisplay();
  });
</script>

🧠 なぜこの実装にしたのか?

関数 / 処理 説明
formatTime(seconds) 秒数を「00:00」形式に整形。padStart(2, '0') を使って桁を揃えることで視認性を確保。
updateDisplay() タイマーの残り時間をDOMに反映。remainingTimeが変化した時に呼び出すことで、UI更新の一元化を実現。
startTimer(duration) 指定時間でタイマーをスタート。setIntervalで毎秒減算し、0になったら終了処理を実行。多重起動防止にも対応。
startBtn.addEventListener 開始ボタン。ユーザー入力を秒に換算し、startTimer()を呼び出す。起動中の多重スタートを防止。
stopBtn.addEventListener ストップボタン。clearIntervalを使ってタイマーの一時停止が可能。
resetBtn.addEventListener リセットボタン。タイマーを初期化し、画面表示を00:00に戻す。シンプルな状態管理に貢献。

🔜 次回予告:「#6 全体の構造整理とCSS適用」

次回は、これまで作ってきた HTML / CSS / JavaScript のコードを整理し、

  • より見通しの良い構造
  • ファイルの分離
  • スタイルの明確化

といった実用的な改善を行っていきます。
アプリとしての完成度がぐっと高まるフェーズですのでお楽しみに!


📌 今回の位置づけ(シリーズ進行)

今回も最後までご覧いただきありがとうございます。次回もよろしくお願いします。

Discussion