jQueryでカウントダウン画像を表示させる | AP*DesignFactory | ホームページ制作 Wordpress LPコーディング – 東京 調布を拠点に活動する個人事業主

BLOG

jQueryでカウントダウン画像を表示させる

jQuery/javascript
Posted : 2018.9.20
Update : 2019.1.4

2019/01/04追記一部ブラウザでサンプルページが正しく動作しなかったので修正いたしました。

サイト公開日、商品の発売日、イベント開催日…、などなどいろいろな用途に使えそうなカウントダウン用画像を表示させるためのjQueryスクリプトです。

下記のサイトを参考にいたしました。

https://php-fan.org/jquery-countdown.html

サンプルではセレクトボックスで、カウントダウン終了日を指定できるようにしていますが、実際にはjsファイルに終了日を直接書いて使用します。

いろいろなデザイン・用途に使用できるように画像はclass指定で背景として表示しています。
残り日数によってターゲットのclassが変わります。

カウントダウン画像のサンプルページ

サンプルソース

html

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

css

#countdown{
    width:600px;
    max-width:100%;
    padding-top:66.6666%;
    background:url(../images/def.gif) 0 0 no-repeat;
    background-size:contain !important;
}

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

jQuery

$(function() {
						
		//カウントダウンの終了期日を記入
		var endTime = new Date('01,09,2019, 00:00:00');
		
		var startTime = new Date(new Date().setHours(0, 0, 0, 0));
		var diff  = endTime - startTime;
		var times = 24 * 60 * 60 * 1000;    
		var day   = Math.floor(diff / times)
		
		//カウントダウンの日程に合わせてクラスを追加
		//期日前	
		if(diff > 0){
			if(day == 0){
			$("#countdown").addClass("theday");
			}
			//1日前
			else if(day == 1){
			$("#countdown").addClass("day01");	
			}		
			//2日前(以下略)
			else if(day ==2){
			$("#countdown").addClass("day02");
			}else if(day ==3){
			$("#countdown").addClass("day03");
			}else if(day ==4){
			$("#countdown").addClass("day04");
			}else if(day ==5){
			$("#countdown").addClass("day05");
			}else if(day ==6){
			$("#countdown").addClass("day06");
			}
			else{
			$("#countdown").addClass("day07");
			}
		}else {
			//終了後
			$("#countdown").addClass("dayover");
		}
 });

※サンプルページは、セレクトで指定された日付を指定しているため、上記のコードとは多少違います。

JavaScriptのnew Date()は日本の標準時間を返すとは限らない(9時間ずれている)のですが、カウントダウン終了日と現在の日にちの取得をそれぞれ0時にセットして、カウントダウン日数の計算結果から1日早めることでズレを解消しました。