// JavaScript Document /* * countdown script */ (function($){ $.fn.countdown = function(options){ // オプション項目のデフォルト値を設定 const defaults = { target : '', lasttimeElem: '.timeleft' } // 引数からオプション項目を設定 const config = $.extend(defaults, options); const $this = $(this); let $display; let countdown = { init: function() { try { // 目標日時と表示場所をDateオブジェクト化 const targetdate = new Date(config.target); $display = $this.find(config.lasttimeElem) // 目標日時が正常に入力されているか確認 const lasttime = countdown.getTimeDiff(targetdate); if(config.target === '') { throw new Error("The 'target' option is required."); } else if(isNaN(lasttime)) { throw new Error("The 'target' option contains an invalid date."); } else if ($display.length == 0) { throw new Error("Display element '" + config.lasttimeElem + "' not found."); } // カウントダウン処理を呼び出し countdown.timer(targetdate); } catch(e) { window.console.error(e); return false; } }, timer: function(targetdate) { // 読み込み完了時の表示処理 let lefttime = countdown.getTimeDiff(targetdate); countdown.updateDispley(lefttime); // タイマー処理 if(lefttime > 0) { // 残り時間があればカウントダウン処理を開始 const timerID = window.setInterval(function(){ // 残り時間の計算 lefttime = countdown.getTimeDiff(targetdate); countdown.updateDispley(lefttime); if(lefttime == 0) { clearInterval(timerID); } }, 1000); } }, getTimeDiff: function(targetdate){ // 現座日時をDateオブジェクト形式で取得 const nowdate = new Date(); let timediff = targetdate - nowdate; if( timediff < 0 ){ timediff = 0; } return timediff; }, updateDispley: function(lefttime) { // lefttime(ms)を単一ごとに分解 // const leftsec = Math.floor(lefttime / 1000) % 60; // const leftmin = Math.floor(lefttime / 1000 / 60) % 60; // const lefthour = Math.floor(lefttime / 1000 / 3600) % 24; const leftday = Math.floor(lefttime / 1000 / 3600 / 24); // ゼロパディング処理 // const dsec = String(leftsec).padStart(2, "0"); // const dmin = String(leftmin).padStart(2, "0"); // const dhour = String(lefthour).padStart(2, "0"); // const dday = String(leftday).padStart(2, "0"); // 表示処理 const str = leftday; $display.text(str); } }; // イベントハンドラ $(function(){ countdown.init(); }); }; })(jQuery);