Skill/Javascript

JS/jQuery - 0부터 숫자 증가하는 카운트 애니메이션 (+ 스크롤 도달 했을 때 작동)

2024. 7. 14.
목차

닌니디자인 JS 썸네일

숫자 카운트

0부터 100까지 숫자를 카운트 하거나 천단위나 소수점자리까지 숫자를 카운트 할 수 있다. 응용하면 스크롤해서 해당 페이지에 도달했을때 카운트를 시작 할 수도 있다. 제이쿼리 animate 메소드를 사용하면 어렵지 않게 구현할 수 있다.

 

 

$('.count-num').each(function(index) {
  var $this = $(this);
  var countFrom = $this.attr('data-from');
  var isComma = /^[0-9]+\.?[0-9]+$/;
  var countTo = $this.attr('data-count');
  var speed = Math.floor($this.attr('data-duration')); 
  var num;

  $({ val: countFrom }).delay(index * 300).animate({ val: countTo }, {
    duration: speed, // 애니메이션이 완료될때까지 걸리는 시간
    easing:'linear', // 애니메이션 효과 방식
    step: function() { 
      if(isComma.test(countFrom)) {
        num = numberWithCommas(parseFloat(this.val).toFixed(1)); //소수점 한자리 까지 표시
      } else {
        num = numberWithCommas(Math.floor(this.val));
      }
      $this.text(num);
    },
    complete: function() { 
      if (Number.isInteger(this.val)){
        num = numberWithCommas(Math.floor(this.val));
      } else {
        num = numberWithCommas(this.val.toFixed(1)); //소수점 한자리 까지 표시
      }
      $this.text(num);
    }
  }); 
});

function numberWithCommas(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

 

카테고리 다른 글 더보기