
“PureJS Counter” is a script written in pure JavaScript that allows animated number display in HTML elements when they come into the user’s viewport. The script uses the Intersection Observer API, making it efficient and resource-optimized. It does not require any external libraries such as jQuery, making it lightweight and easy to implement.
Below, I detail the code operation.
Script structure
1. Listening for the DOMContentLoaded
event
The script runs only after the entire DOM tree is loaded. This ensures that the elements we are working with are available in the document:
document.addEventListener("DOMContentLoaded", function() {
2. counterStartUp
function
The main function responsible for number animation. It takes a single HTML element as a parameter. It works in several steps:
a) Fetching parameters
Funkcja odczytuje atrybuty elementu HTML, które definiują sposób działania licznika:
data-counter-start
– initial value (default0
).data-counter-step
– counter step size (default1
).data-counter-duration
– nimation duration in milliseconds (default4000
ms).data-counter-before
anddata-counter-after
– text displayed before and after the number (e.g.,+
,%
).- Target value – read as the text content of the element (e.g.,
<span>100</span>
).
b) Calculating interval
The interval length is calculated based on the time parameters and counter range:
let interval = Math.ceil(duration / (end - start) * step);
This ensures the counter operates smoothly, regardless of the number range.
c) Number animation
Using the setInterval
function, the counter is incremented by the step value (step
) at set time intervals. Once the target value is reached, the counter stops:
if (counter >= end) {
counter = end;
clearInterval(intervalId);
}
d) Updating the element
At each step, the number is updated in the HTML element, including the preceding and following text
element.innerHTML = counterBefore + counter + counterAfter;
3. Intersection observer
To improve efficiency, the counter is activated only when the element appears in the user’s viewport. This uses the Intersection Observer API:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
counterStartUp(entry.target);
observer.unobserve(entry.target);
}
});
}, { threshold: 0.5 });
threshold: 0.5
– the counter starts when at least 50% of the element is in the visible area.observer.unobserve(entry.target)
– after starting the counter, the element is removed from observation to save resources.
4. Counter initialization
The script finds all HTML elements with the attribute data-counter="true"
and starts the observer on them
document.querySelectorAll('[data-counter="true"]').forEach(function(element) {
observer.observe(element);
});
Example HTML
Here’s an example of the code in practice:
<div data-counter="true"
data-counter-start="0"
data-counter-step="5"
data-counter-duration="2000"
data-counter-before="+"
data-counter-after="%">
100
</div>
- The counter starts at
0
. - It increases by
5
. - The animation lasts
2000
ms. - The
+
sign is added before the number, and%
after. - The final value will be
100
.
Use Cases
The script is ideal for dynamically presenting statistics such as:
- Number of clients or users.
- Percentage values.
- Numeric data on sales pages.
Summary
“PureJS Counter” is an efficient and easy-to-use counter in pure JavaScript. By using the Intersection Observer API, animations are activated only when the user actually sees them, improving performance and UX. This code is versatile, flexible, and easy to customize, making it an excellent tool for modern websites.