block by EE2dev 59d46c9f9b406eca00a8429f9b3dc831

Transitioning a text counter

Full Screen

Built with blockbuilder.org

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<style>

h1 {
  font: 400 120px/500px "Helvetica Neue";
  text-align: right;
  width: 960px;
  height: 500px;
  margin: 0;
}

</style>

<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>

var localeGerman = d3.formatDefaultLocale({
      "decimal": ",",
      "thousands": ".",
      "grouping": [3],
      "currency": ["€", ""] //if you want a space between €-sign and number, add it here in the first string 
    });
var format = localeGerman.format(",.2f");

transitionCounter(33, 8748.894, format, " Kunden")

function transitionCounter(numberStart, numberEnd, numberFormat, numberUnit) {
  let data = [numberFormat(numberStart)];
  const dj = d3.selectAll("h1")
    .data(data);

  const sel = dj.enter()
    .append("h1")
    .merge(dj)
    .text((d) => d + numberUnit);
    
  sel.transition()
      .duration(2500)
      .on("start", function repeat() {
        d3.active(this)
            .tween("text", function() {
              var that = d3.select(this),
                  // i = d3.interpolateNumber(that.text().replace(/[,.]/g, ""), numberEnd);
                i = d3.interpolateNumber(numberStart, numberEnd);
              return function(t) { that.text(format(i(t)) + numberUnit); };
            })
      });
}

</script>
</body>
</html>