In JavaScript, a counter is typically a variable or data structure used to keep track of a numeric value and perform operations to increment or decrement its value. It is commonly used in various programming scenarios, such as counting iterations, tracking elements, or implementing features like progress indicators or pagination. In this article we will be creating a simple counter which you can decrease or increase the number.
Implementing a counter
A counter can be implemented using a simple variable and manipulating its value with the addition ('+=')
and subtraction ('-=')
operators. Let's see the example below.
Create an index.html
file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Counter Program - JS</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<label id="countLabel">0</label>
<button id="decreaseBtn">decrease</button>
<button id="resetBtn">reset</button>
<button id="increaseBtn">Increase</button>
</div>
//added script file
<script src="script.js"></script>
</body>
</html>
also, create a script.js file and include in your html file below like so.<script src="script.js"></script>
. In your js file, write this code.
let count = 0;
document.getElementById("decreaseBtn").onclick = function(){
count -=1;
document.getElementById("countLabel").innerHTML = count;
}
document.getElementById("resetBtn").onclick = function(){
count =0;
document.getElementById("countLabel").innerHTML = count;
}
document.getElementById("increaseBtn").onclick = function(){
count +=1;
document.getElementById("countLabel").innerHTML = count;
}
and here our following outputs.
Increasing value.
Conclusion.
A counter is typically a variable or data structure used to keep track of a numeric value and perform operations to increment or decrement its value.
A counter can be implemented using a simple variable and manipulating its value with the addition ('+=')
and subtraction ('-=')
operators.
Top comments (0)