JavaScript Count Up

JavaScript Count Up
Project: Count Up
Author: Hakan Havutcuoglu
Edit Online: View on CodePen
License: MIT

This JavaScript code snippet helps you to create a count up. It defines a jQuery plugin for counting up numbers when they come into view on a webpage. The script first checks whether the element is in view, and then applies a class to the element to initiate the count-up animation. The plugin has default options for the starting number, ending number, animation speed, refresh interval, and number of decimal places to show.

The plugin also allows for custom functions to be called on update and on completion of the count-up animation. The script includes an event listener that calls the update function when the window is scrolled or loaded, and a button that resets the animation.

How to Create JavaScript Count Up

Create the HTML structure for the count up as follows:

<div class="title"><h1>Count Up</h1></div>
<div class="container">
	<div class="count_up animate">
		<div class="counterbox-container">
			<p class="number">
			<span class="prefix">$</span>
			<span class="value" data-seperator="." data-decimal="2" data-count="9256.58">9256.58</span>
			</p>
			<p class="headline">Profit</p>
			<p class="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</p>
		</div>
	</div>

	<div class="count_up animate">
		<div class="counterbox-container">
			<p class="number">
			<span class="value" data-seperator="" data-decimal="2" data-count="99.99">99.99</span>
			<span class="suffix">%</span>
			</p>
			<p class="headline">Success</p>
			<p class="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</p>
		</div>
	</div>

	<div class="count_up animate">
		<div class="counterbox-container">
			<p class="number">
			<span class="value" data-seperator="." data-decimal="0" data-count="2158">2158</span>
			</p>
			<p class="headline">Customers</p>
			<p class="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</p>
		</div>
	</div>
</div>
<div class="button">
	<button class="start">Count up again</button>
</div>

Style count up using the following CSS styles:

/**
 * Count Up Script with jQuery
 * Copyright by havutcuoglu
 * https://codepen.io/havutcuoglu/pen/bGKBWvJ
 * This notice MUST stay intact in CSS and Script file for free and legal usege.
 */
body {
  font-family: sans-serif;
  font-size: 16px;
  margin-top: 10vh;
  background: #000000;
  color: #ffffff;
}

h1 {
  font-size: 52px;
  text-align: center;
  margin-bottom: 3rem;
}

.container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: stretch;
  align-content: flex-start;
  gap: 30px;
}

.count_up {
  align-self: auto;
  flex-basis: auto;
  padding: 15px;
  color: #ffffff;
  background: #8624ab;
  background: linear-gradient(125deg, #8624ab 13%, #e7020c 100%);
  border-radius: 5px;
  text-align: center;
}
.count_up .number {
  font-size: 36px;
  font-weight: 600;
  margin-bottom: 8px;
}
.count_up .headline {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
}
.count_up .text {
  font-size: 16px;
  margin-top: 32px;
  font-weight: 400;
  color: #aaaaaa;
}

.button {
  text-align: center;
}
.button button {
  text-align: center;
  padding: 10px 40px;
  background: #dedede;
  font-size: 21px;
  border-radius: 5px;
  border: none;
  margin: 50px auto 0;
  cursor: pointer;
  transition: all 300ms ease;
}
.button button:hover {
  background: #c1c706;
}

Load the following scripts before closing the body tag:

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js'></script>

Finally, add the following JavaScript function for its functionality:

/**
 * Count Up Script with jQuery
 * Copyright by havutcuoglu
 * https://codepen.io/havutcuoglu/pen/bGKBWvJ
 * This notice MUST stay intact in CSS and Script file for free and legal usege.
 */
// ++++++++++++++++++++++++++++++
// view area function to start the animation
var element_to_animate = $('.animate');
var $window = $(window);

// function to check element in view area
function into_view_area() {
	var window_height = $window.height();
	var window_top_position = $window.scrollTop();
	var window_bottom_position = (window_top_position + window_height);

	// calculate view area
	$.each(element_to_animate, function() {
		var element_height = $(this).outerHeight();
		var element_top_position = $(this).offset().top;
		var element_bottom_position = (element_top_position + element_height);
 
		//check to see if this current element is within viewport
		if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) {
			$(this).addClass('in_view');
		}
		else {
			$(this).removeClass('in_view');
		}
	});
}

// initialize function
$window.on('scroll resize', into_view_area);
$window.trigger('scroll');


// ++++++++++++++++++++++++++++++++++++
// counter box to count up the number from 0 to defined value

$.fn.countTo = function(options) {
	// merge the default plugin settings with the custom options
	options = $.extend({}, $.fn.countTo.defaults, options || {});

	// how many times to update the value, and how much to increment the value on each update
	var loops = Math.ceil(options.speed / options.refreshInterval),
		increment = (options.to - options.from) / loops;

	return $(this).each(function() {
		var _this = this,
			loopCount = 0,
			value = options.from,
			interval = setInterval(updateTimer, options.refreshInterval);

		// update value by loops
		function updateTimer() {
			value += increment;
			loopCount++;

			// add decimal and change string to number
			var valueWithDecimal = value.toFixed(options.decimals),
				valueAsNumber = Number.parseFloat(valueWithDecimal);

			// output frontend
			var valueAsLocaleNumber = valueAsNumber.toLocaleString();
			//$(_this).html(valueAsLocaleNumber);
			$(_this).html(valueAsLocaleNumber.replace(/\./g,$(_this).data('seperator')));

			// custom functions on update
			if (typeof(options.onUpdate) == 'function') {
				options.onUpdate.call(_this, value);
			}

			// custom functions on complete
			if (loopCount >= loops) {
				clearInterval(interval);
				value = options.to;

				if (typeof(options.onComplete) == 'function') {
					options.onComplete.call(_this, value);
				}
			}
		}
	});
};

// default options
$.fn.countTo.defaults = {
	from: 0,  // the number the element should start at
	to: 100,  // the number the element should end at
	speed: 1000,  // how long it should take to count between the target numbers
	refreshInterval: 100,  // how often the element should be updated
	decimals: 0,  // the number of decimal places to show
	onUpdate: null,  // callback method for every time the element is updated,
	onComplete: null,  // callback method for when the element finishes updating
};



// get the element and start to count number in view area
function updateOptions() {
	var element = $('.count_up');
	
	element.each(function() {
		if($(this).hasClass('in_view') && !$(this).hasClass('is_done')) {
			$(this).addClass('is_running');

			if($(this).hasClass('is_running')) {
				$(this).find('.value').countTo({
					from: 0
					,to: $(this).find('.value').data('count')
					,speed: 3000
					,refreshInterval: 50
					,decimals: $(this).find('.value').data('decimal')
					,onUpdate: function(value) {
						element.addClass('is_done');
					}
					,onComplete: function(value) {
						element.removeClass('is_running');
					}
				});
			}
		}
	});
}
$(window).on('scroll load', function() {
    updateOptions();
});

$('button.start').click(function() {
	$('.count_up').removeClass('is_done');
	$('.count_up').removeClass('in_view');
	into_view_area();
	updateOptions();
});

That’s all! hopefully, you have successfully integrated the JavaScript code for the Count Up. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *