Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <body>
  <div id="root"></div>
</body>
              
            
!

CSS

              
                * {
  margin: 0;
}

html, body {
  height: 100%;
  width: 100%;
}

#root {
  height: 100%;
  width: 100%;
  background: radial-gradient(
    ellipse farthest-corner at center top,
    #012619,
    #000
  );
  font-family: 'Comfortaa', cursive;
}

.App { 
  height: 100%;
  width: 100%;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.ticker-view {
  height: auto;
  display: flex;
  flex-direction: row-reverse;
  overflow: hidden;
  position: relative;
}

.number-placeholder {
  visibility: hidden;
}

.ticker-column-container {
  position: relative;
}

.ticker-column {
  position: absolute;
  height: 1000%;
  bottom: 0;
}

.ticker-digit {
  width: auto;
  height: 10%;
}

.ticker-column.increase {
  animation: pulseGreen 500ms cubic-bezier(0.4, 0, 0.6, 1) 1;
}

.ticker-column.decrease {
  animation: pulseRed 500ms cubic-bezier(0.4, 0, 0.6, 1) 1;
}

@keyframes pulseGreen {
  0%,
  100% {
    color: inherit;
  }

  50% {
    color: var(--increment-color);;
  }
}

@keyframes pulseRed {
  0%,
  100% {
    color: inherit;
  }

  50% {
    color: var(--decrement-color);
  }
}

input[type="range"] {
  margin-top: 24px;
  width: 250px;
  -webkit-appearance: none;
  height: 7px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 5px;
  background-image: linear-gradient(#73d46a, #73d46a);
  background-repeat: no-repeat;
}

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  height: 20px;
  width: 20px;
  border-radius: 50%;
  background: #73d46a;
  cursor: pointer;
  box-shadow: 0 0 2px 0 #555;
  transition: background 0.3s ease-in-out;
}

input[type="range"]::-webkit-slider-runnable-track {
  -webkit-appearance: none;
  box-shadow: none;
  border: none;
  background: transparent;
}

input[type="range"]::-webkit-slider-thumb:hover {
  box-shadow: #73d46a50 0px 0px 0px 8px;
}

input[type="range"]::-webkit-slider-thumb:active {
  box-shadow: #73d46a50 0px 0px 0px 11px;
  transition: box-shadow 350ms cubic-bezier(0.4, 0, 0.2, 1) 0ms,
    left 350ms cubic-bezier(0.4, 0, 0.2, 1) 0ms,
    bottom 350ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;
}


              
            
!

JS

              
                // Full open-source React component available via npm
// https://www.npmjs.com/package/react-animated-counter
import React, {
	useState,
	useEffect,
	useRef
} from "https://cdn.skypack.dev/react@17.0.1";
import ReactDOM from "https://cdn.skypack.dev/react-dom@17.0.1";
import { motion } from "https://cdn.skypack.dev/framer-motion@5.5.5";

// Utility function for formatting numbers
const formatForDisplay = (number, includeDecimals, decimalPrecision, includeCommas) => {
  const decimalCount = includeDecimals ? decimalPrecision : 0;
  const parsedNumber = parseFloat(`${Math.max(number, 0)}`).toFixed(decimalCount);
  const numberToFormat = includeCommas 
    ? parseFloat(parsedNumber).toLocaleString('en-US', { minimumFractionDigits: includeDecimals ? decimalPrecision : 0 }) 
    : parsedNumber;
  return numberToFormat.split('').reverse();
};

// Custom hook for tracking previous values
const usePrevious = (value) => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    ref.current = value;
  }, [value]);
  return ref.current;
};

// Debounce utility
const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

// Decimal element component
const DecimalColumn = ({ fontSize, color, isComma, digitStyles }) => (
  <span
    style={{
      fontSize: fontSize,
      lineHeight: fontSize,
      color: color,
      marginLeft: `calc(-${fontSize} / 10)`,
      ...digitStyles,
    }}>
    {isComma ? ',' : '.'}
  </span>
);

// Individual number element component
const NumberColumn = React.memo(({
  digit,
  delta,
  fontSize,
  color,
  incrementColor,
  decrementColor,
  digitStyles,
  animateInitialValue = true,
}) => {
  const [position, setPosition] = React.useState(0);
  const [animationClass, setAnimationClass] = React.useState(null);
  const [isInitialized, setIsInitialized] = React.useState(false);
  const currentDigit = +digit;
  const previousDigit = usePrevious(+currentDigit);
  const columnContainer = React.useRef(null);

  const handleAnimationComplete = React.useCallback(
    debounce(() => {
      setAnimationClass("");
    }, 200),
    []
  );

  const setColumnToNumber = React.useCallback((number, animate = true) => {
    if (columnContainer?.current?.clientHeight) {
      const newPosition = columnContainer.current.clientHeight * parseInt(number, 10);
      setPosition(newPosition);
    }
  }, []);

  React.useLayoutEffect(() => {
    if (!isInitialized && columnContainer?.current?.clientHeight) {
      setColumnToNumber(digit, animateInitialValue);
      setIsInitialized(true);
    }
  }, [digit, setColumnToNumber, isInitialized, animateInitialValue]);

  React.useEffect(() => {
    if (isInitialized) {
      setAnimationClass(previousDigit !== currentDigit ? delta : '');
    }
  }, [digit, delta, isInitialized]);

  React.useEffect(() => {
    if (isInitialized) {
      setColumnToNumber(digit);
    }
  }, [digit, setColumnToNumber, isInitialized]);

  // If digit is negative symbol, simply return an unanimated character
  if (digit === '-') {
    return (
      <span
        style={{ 
          color: color,
          fontSize: fontSize,
          lineHeight: fontSize,
          marginRight: `calc(${fontSize} / 5)`,
          ...digitStyles
        }}
      >
        {digit}
      </span>
    );
  }

  return (
    <div
      className='ticker-column-container'
      ref={columnContainer}
      style={{ 
        fontSize: fontSize,
        lineHeight: fontSize,
        height: 'auto',
        color: color,
        '--increment-color': `${incrementColor}`,
        '--decrement-color': `${decrementColor}`,
        ...digitStyles,
      }}
    >
      <React.motion.div
        animate={{ x: 0, y: position }}
        className={`ticker-column ${animationClass}`}
        onAnimationComplete={handleAnimationComplete}
        initial={animateInitialValue ? { x: 0, y: 0 } : { x: 0, y: position }}
      >
        {[9, 8, 7, 6, 5, 4, 3, 2, 1, 0].map((num) => (
          <div className='ticker-digit' key={num}>
            <span style={{ 
              fontSize: fontSize,
              lineHeight: fontSize,
              ...digitStyles,
            }}>
              {num}
            </span>
          </div>
        ))}
      </React.motion.div>
      <span className='number-placeholder'>0</span>
    </div>
  );
}, (prevProps, nextProps) => prevProps.digit === nextProps.digit && prevProps.delta === nextProps.delta);

// Main component
const AnimatedCounter = ({
  value = 0,
  fontSize = '18px',
  color = 'black',
  incrementColor = '#32cd32',
  decrementColor = '#fe6862',
  includeDecimals = true,
  decimalPrecision = 2,
  includeCommas = false,
  containerStyles = {},
  digitStyles = {}, 
  animateInitialValue = false,
}) => {
  const numArray = formatForDisplay(Math.abs(value), includeDecimals, decimalPrecision, includeCommas);
  const previousNumber = usePrevious(value);
  const isNegative = value < 0;

  let delta = null;

  if (previousNumber !== null) {
    if (value > previousNumber) {
      delta = 'increase';
    } else if (value < previousNumber) {
      delta = 'decrease';
    }
  }

  return (
    <motion.div
      layout
      className='ticker-view'
      style={{ ...containerStyles }}
    >
      {/* Format integer to NumberColumn components */}
      {numArray.map((number, index) =>
        number === "." || number === "," ? (
          <DecimalColumn
            key={index}
            fontSize={fontSize}
            color={color}
            isComma={number === ","}
            digitStyles={digitStyles}
          />
        ) : (
          <NumberColumn
            key={index}
            digit={number}
            delta={delta}
            color={color}
            fontSize={fontSize}
            incrementColor={incrementColor}
            decrementColor={decrementColor}
            digitStyles={digitStyles}
            animateInitialValue={animateInitialValue}
          />
        )
      )}
      {/* If number is negative, render '-' feedback */}
      {isNegative &&
        <NumberColumn
          key={'negative-feedback'}
          digit={'-'}
          delta={delta}
          color={color}
          fontSize={fontSize}
          incrementColor={incrementColor}
          decrementColor={decrementColor}
          digitStyles={digitStyles}
          animateInitialValue={animateInitialValue}
        />
      }
    </motion.div>
  );
};

// App component with slider
const App = () => {
  const [value, setValue] = React.useState(0);

  return (
    <div className="App">
      <AnimatedCounter
        value={value}
        fontSize="120px"
        color="white"
        incrementColor="#73d46a"
        decrementColor="#fe6862"
        includeDecimals={false}
        includeCommas={true}
      />
      <input
        type="range"
        min="0"
        max="1000"
        value={value}
        onChange={(e) => setValue(parseInt(e.target.value))}
        style={{
          marginTop: '24px',
          width: '250px'
        }}
      />
    </div>
  );
};

// Render the app
ReactDOM.render(<App />, document.getElementById('root'));

              
            
!
999px

Console