【jQuery】5〜0までカウントダウンするスクリプト
- 2018年11月8日
- jQuery
HTMLを用意
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="countdown"></div> <button type="button" id="btnStart">START</button> </body> </html>
<div id="countdown"></div>
↑この部分にカウントを表示します。
<button type="button" id="btnStart">START</button>
↑このボタンをクリックで5からカウントを開始、0になったら止まるようにします。
↓こんな感じにします。

javascriptでは jqueryを読み込み
カウントダウンスクリプトを記述します。
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script>
$(function(){
$('#btnStart').on('click',function(){
cnt = 5; //5秒前からカウントスタート
$('#countdown').text(cnt);
cnDown = setInterval(function(){ //1秒おきにカウントマイナス
cnt--;
if(cnt <= 0){//0になったら停止する
clearInterval(cnDown);
}
$('#countdown').text(cnt);
},1000);
});
});
</script>
すべてガッチャンコして↓こんなソースコードにします。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="countdown"></div>
<button type="button" id="btnStart">START</button>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script>
$(function(){
$('#btnStart').on('click',function(){
cnt = 5; //5秒前からカウントスタート
$('#countdown').text(cnt);
cnDown = setInterval(function(){ //1秒おきにカウントマイナス
cnt--;
if(cnt <= 0){//0になったら停止する
clearInterval(cnDown);
}
$('#countdown').text(cnt);
},1000);
});
});
</script>
</body>
</html>
以上、jQueryによる5〜0までカウントダウンするスクリプトでした。
