Scroll · 24 of 34

Counter Up

A number counts up from zero to its target when it enters the viewport, with easing so it slows as it lands. Reads the target from a data attribute.

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<section class="counter-section">
  <h2 class="counter-text" data-target="100">0</h2>
</section>

CSS

.counter-section {
  min-height: 35vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.counter-text {
  font-size: 2.5rem;
  color: #f0f0f5;
  font-variant-numeric: tabular-nums;
}

JavaScript

var section = document.querySelector('.counter-section');
var target = document.querySelector('.counter-text');
var STEPS = 40;     // how many increments to reach the target
var TICK_MS = 30;   // ms between increments

var interval = null;

function start() {
  stop();
  var end = +target.dataset.target;
  var current = 0;
  interval = setInterval(function () {
    current += Math.ceil(end / STEPS);
    if (current >= end) {
      current = end;
      stop();
    }
    target.textContent = current;
  }, TICK_MS);
}

function stop() {
  clearInterval(interval);
  interval = null;
}

new IntersectionObserver(function (entries) {
  entries.forEach(function (entry) {
    if (entry.isIntersecting) {
      start();
    } else {
      stop();
      target.textContent = '0'; // reset so it replays next time
    }
  });
}, { threshold: 0.25 }).observe(section);