숫자 카운터; 배열에 있는 숫자 애니메이션으로 카운터
2022. 4. 29. 17:14ㆍWEB/jQuery
버튼을 클릭했을 때 숫자가 애니메이션 효과로 카운터 된다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
<div class="wrap">
<div class="btn-wrap">
<button type="button">버튼100</button>
<button type="button">버튼200</button>
<button type="button">버튼300</button>
</div>
<div class="num-wrap">
<span id="num1">0</span>
<span id="num2">0</span>
<span id="num3">0</span>
</div>
</div>
<script>
$(function(){
// 숫자 카운트 애니메이션
function numberCounter(target_frame, target_number) {
this.count = 0;
this.diff = 0;
this.target_count = parseInt(target_number);
this.target_frame = document.getElementById(target_frame);
this.timer = null;
this.counter();
};
numberCounter.prototype.counter = function() {
var self = this;
this.diff = this.target_count - this.count;
if(this.diff > 0) {
self.count += Math.ceil(this.diff / 5);
}
this.target_frame.innerHTML = this.count.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
if(this.count < this.target_count) {
this.timer = setTimeout(function() { self.counter(); }, 30);
} else {
clearTimeout(this.timer);
}
};
var btn = $('.btn-wrap').find('button');
btn.on('click', function(){
var $this = $(this),
btnIdx = btn.index($this),
// btnData = btn.attr('data-size'),
num = [
{num1: "100", num2: "100", num3: "100"},
{num1: "200", num2: "200", num3: "200"},
{num1: "300", num2: "300", num3: "300"}
];
num1 = num[btnIdx].num1;
num2 = num[btnIdx].num2;
num3 = num[btnIdx].num3;
new numberCounter("num1", num1);
new numberCounter("num2", num2);
new numberCounter("num3", num3);
})
})
</script>
</body>
</html>