カウントダウンで背景画像を切り替える(Vanilla JS版)

2025-9-3 / last up date:2025-9-3 JavaScript

以前 jQueryで作ったカウントダウン をVanillaJS版として手直ししました。

html + JavaScript

<div id="countdown"></div>

<script>
(function () {
  // カウントダウンを表示する要素
  const target = document.getElementById("countdown");

  // 使用するクラス名一覧(付与/削除対象をまとめて管理)
  const CD_CLASSES = [
    "theday","day01","day02","day03","day04","day05","day06","day07","dayover"
  ];

  // 指定した日付を「その日の0:00」に揃える関数
  function atMidnight(d) {
    return new Date(d.getFullYear(), d.getMonth(), d.getDate());
  }

  // 既に付いているカウントダウンクラスを一旦すべて削除
  function clearClasses(el) {
    CD_CLASSES.forEach(cls => el.classList.remove(cls));
  }

  // 終了日と今日を比較して、対応するクラスを付与
  function applyCountdownClass(endTime) {
    const today0 = atMidnight(new Date()); // 今日の0:00
    const end0   = atMidnight(endTime);    // 終了日の0:00

    const diff   = end0 - today0;          // 残り日数(ミリ秒)
    const oneDay = 24 * 60 * 60 * 1000;    // 1日分のミリ秒
    const days   = Math.floor(diff / oneDay); // 残り日数(整数)

    clearClasses(target); // 古いクラスを削除

    if (diff < 0) {
      // 期日を過ぎた場合
      target.classList.add("dayover");
    } else if (days === 0) {
      // 当日の場合
      target.classList.add("theday");
    } else {
      // 1日以上残っている場合(最大7日分まで用意)
      const n = Math.min(days, 7);
      target.classList.add("day" + String(n).padStart(2, "0"));
    }
  }

  // ★ 終了日をここで指定(ISO形式で記述)
  const endTime = new Date("2025-12-24T00:00:00+09:00");

  // 実行してクラスを付与
  applyCountdownClass(endTime);
})();
</script>

CSS(例)

#countdown {
  width: 600px;
  max-width: 100%;
  aspect-ratio: 3 / 2;
  background: url(../images/def.gif) no-repeat 0 0 / contain;
}

#countdown.day01 { background-image: url(../images/countdown_01.gif); }
#countdown.day02 { background-image: url(../images/countdown_02.gif); }
#countdown.day03 { background-image: url(../images/countdown_03.gif); }
#countdown.day04 { background-image: url(../images/countdown_04.gif); }
#countdown.day05 { background-image: url(../images/countdown_05.gif); }
#countdown.day06 { background-image: url(../images/countdown_06.gif); }
#countdown.day07 { background-image: url(../images/countdown_07.gif); }
#countdown.theday { background-image: url(../images/countdown_00.gif); }
#countdown.dayover { background-image: url(../images/countdown_over.gif); }

サンプルページ

カレンダーから日付を選んで試せるデモページも用意しました。
カウントダウンサンプルはこちら

掲載しているコードや設定例は動作を保証するものではありません。
利用は自己責任で行い、必ずテスト環境での確認を行ってください。