How to make your own countUp.js plugin using JavaScript ?
Last Updated :
18 Jan, 2021
prerequisite:
- Document Object Model ( DOM )
- Use of Classes in ES6
If you are a beginner in JavaScript and have basic programming knowledge then don’t worry, you have landed in a perfect place.
Let us divide the problem into multiple segments:
- Implementing a simple structure using HTML.
- Providing a basic display style using CSS.
- The main programming to implement, the behavior using JavaScript
- onclick=”….( )” : To trigger the function
- Creating a class with the name Counter
- Using a constructor to initialize the class
- Creating the method/function with the name shoot( ) for animation
- Calling the method shoot from the class Counter
Step 1: Implementing the HTML
HTML
< div class = "container" >
< img src =
< div class = "main" >
< h1 id = "counter" > _______ </ h1 >
< button onclick = "trigger()" > START </ button >
</ div >
</ div >
< script >
// Including JavaScript Code
</ script >
|
Step 2: Implementing the CSS
CSS
.container {
display : flex;
padding : 20px ;
}
.main{
padding : 20px ;
}
button{
width : 100px ;
height : 45px ;
background-color : #33ff33 ;
border-radius: 10px ;
}
|
Step 3: JavaScript
Javascript
class Counter {
constructor(data) {
this .start = data[ "start" ];
this .end = data[ "end" ];
this .frames = data[ "frames" ];
this .step = data[ "step" ];
this .target = data[ "target" ];
}
shoot() {
var count = 0;
var stepArray = [];
document.getElementById( this .target)
.innerHTML = this .start;
while ( this .end > this .start) {
this .start += this .step;
stepArray[count++] = this .start;
}
var functional_target = this .target;
for (let i = 0; i < count; i++) {
setTimeout( function () {
document.getElementById(functional_target)
.innerHTML = stepArray[i];
}, (i + 1) * this .frames);
}
setTimeout( function () {
document.getElementById(
functional_target).innerHTML = this .end;
}, count * frames);
}
}
var animate = new Counter({
start: 100000,
end: 2000000,
frames: 1,
step: 1000,
target: "counter"
});
function trigger() {
animate.shoot();
}
|
Output:
Custom Countup Preview
Main Used Functions:
OVERVIEW
The flow of the Program
This is the basic prototype of the custom countUp.js that we can implement using the concept of Class in JavaScript.
One can also use their own function to render the values in specific ways.
Share your thoughts in the comments
Please Login to comment...