Animated counter

by Sasá Rafalsky

HTML

<div class="number">000.0 $</div>
<button id="animate" onclick="animateCounter(event)">Animate</button>

SCSS

@import url('https://fonts.googleapis.com/css?family=IBM+Plex+Sans:400,700');
* {
  margin:0;
}
* + * {
  margin-top:10px;
}
body {
  background-color:#eee;
  margin:0;
  padding:20px;
}
body,button {
  font-family:'IBM Plex Sans',sans-serif;
  font-size:1.2rem;
  line-height:1.5;
}
button {
  background-color:#eee;
  border:1px #999 solid;
  border-radius:4px;
  cursor:pointer;
  padding:5px 15px;
  transition:all 250ms;
}
button:hover {
  background-color:white;
}
#desc {
  padding:40px;
}
.number {
  font-weight: normal;
  display:block;
  font-size:6rem;
  line-height:6.5rem;
  * + * {
    margin-top:0;
  }
}
.digit-con {
  display:inline-block;
  height:6.5rem;
  overflow:hidden;
  vertical-align:top;
  span {
    display:block;
    font-size:6rem;
    line-height:6.5rem;
    position:relative;
    text-align:center;
    top:0;					
    width:0.55em;
  }
}

JavaScript

function Counter(obj){
  console.log('OBJ:', obj);
  
  var number = "311.2 $";
  
  console.log("N:", number);
  
  // clear the HTML element
  obj.empty();
  console.log('OBJ EMP:', obj);
  
  // create an array from the text, prepare to identify which characters in the string are numbers
  var numChars = number.split("");
  var numArray = [];
  var setOfNumbers = [0,1,2,3,4,5,6,7,8,9];

  // for each number, create the animation elements
  for(var i=0; i<numChars.length; i++) { 
  console.log("obj", obj);
  
   if (setOfNumbers.indexOf(parseInt(numChars[i], 10)) !== -1) {
      obj.append('<span class="digit-con"><span class="digit'+numArray.length+'">0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br></span></span>');
      numArray[numArray.length] = parseInt(numChars[i], 10);
    } else {
      obj.append('<span>'+numChars[i]+'</span>');
    } 
  }

  // determine the height of each number for the animation
  var increment = obj.find('.digit-con').outerHeight();
  console.log("increment", increment);
  var speed = 2000;
  
  // animate each number
  for(var i=0; i<numArray.length; i++) {
    obj.find('.digit'+i).animate({top: -(increment * numArray[i])}, Math.round(speed / (1 + (i * 0.333))));
  }
}




$("#animate").click(function(){
  $('.number').eq(0).text($('.number').attr('data-number'));
  Counter($('.number').eq(0));
  console.log("AA", $('.number').eq(0));
});



function animateCounter(ev) {
	console.log("animate", ev);
}