JSFiddle - React, Tailwind, and code Playground

by BurpmanJunior

HTML

<span data-countup-to="100.25" data-countup-from="10" data-countup-duration="1000"></span>

JavaScript

/**
 */
class CountUp{

  /**
   * Create an instance of CountUp.
   *
   * Options are read from data attributes.
   *
   * `data-countup-to` (required) Number to count to. Decimal formatting is preserved
   *
   * `data-countup-from` (default = 0) Initial number
   *
   * `data-countup-duration` (default = 3000) Duration of animation in milliseconds
   *
   * @since 1.0.0
   *
   * @example <!-- Count from 0 up to 100 over 3 seconds -->
   * <span data-countup-to="100">100</span>
   *
   * <!-- Count from 100 down to 50 over 2 seconds -->
   * <span data-countup-to="50" data-countup-from="100" data-countup-duration="2000">50</span>
   *
   * <!-- Count up to 1.00 preserving the decimal format -->
   * <span data-countup-to="1.00">1.00</span>
   *
   * @param  {Element} elem DOM node
   * @return {CountUp}      Returns false if invalid
   *
   * @memberof CountUp
   */
  constructor(elem){
    // DOM validation
    if(!(elem instanceof Element)){ return false; }
    this.dom = elem;

    // Default settings
    this.settings = {
      duration: 3000,
      from: 0,
    };

    // Settings validation
    try{
      this.getSettings();
    }catch(e){
      this.disabled = true;
      return this;
    }

    this.resetRender();
    return this;
  }


  /**
   * Get settings from [data-countup-*] attributes
   * @since 1.0.0
   *
   * @throws {Error} Will throw on missing a required data attribute
   * @return {Boolean}
   *
   * @memberof CountUp
   */
  getSettings(){
    this.settings = this.settings || {};

    // Lookup keys
    let errors     = null;
    const required = ['to'];
    const optional = ['duration', 'from'];

    // Required
    required.forEach(k => {
      const v = this.dom.getAttribute(`data-countup-${k}`);
      if(v){
        this.settings[k] = v;
      }else{
        throw new Error(`Missing required data attribute: data-countup-${k}`);
      }
    });

    // Optional
    optional.forEach(k => {
      const v =...