jQueryで実装!数字のカウントアップ・カウントダウンアニメーション

by interlife

HTML

<div class="card">
  <div class="card-body">
    <div id="price">
      <span>0</span>
    </div>
    <p>
      <button id="price_up" class="btn btn-raised btn-success mb-2">数値を100増やす</button>
      <button id="price_down" class="btn btn-raised btn-success mb-2">数値を100減らす</button>
    </p>
  </div>
</div>

CSS

.card {
  word-wrap: break-word;
  background-clip: border-box;
  background-color: #fff;
  border: 1px solid hsla(0, 0%, 9%, .125);
  border-radius: 0.25rem;
  display: flex;
  flex-direction: column;
  min-width: 0;
  position: relative;
  color: #333;
  text-align: center;
  margin-top: 20px;
  font-family: sans-serif;
}

.card-body {
  flex: 1 1 auto;
  padding: 1rem;
  font-size: 30px;
}

.btn-success {
  background-color: #198754;
  border-color: #198754;
  color: #fff;
  cursor: pointer;
  padding: 0.5em 1em;
  border-radius: 0.25rem;
  margin: 0 5px;
}

JavaScript

$(function() {
	var price = 0; // 現在の数値を保持する変数

	// ■カウントアップ処理
	$('#price_up').click(function(){
		// {count: 現在値} から {count: 目標値} までアニメーションさせる
		$({count: price}).animate({count: price+100}, {
			duration: 1000, 
			easing: 'linear',
			// progress: アニメーションの途中で毎回実行される関数
			progress: function() {
				// 変化途中の値(this.count)を整数に丸めて表示
				$('#price span').text(Math.ceil(this.count));
			}
		});
		price += 100; // 内部の数値を更新
	});

	// ■カウントダウン処理
	$('#price_down').click(function(){
		if (price <= 0) return false;

		$({count: price}).animate({count: price-100}, {
			duration: 1000,
			easing: 'linear',
			progress: function() {
				$('#price span').text(Math.ceil(this.count));
			}
		});
		price -= 100;
	});
});