Create a program of a simple counter using javascript. Let’s create a simple web page to design and perform the simple counter using HTML CSS javascript.
Problem statement
In this task, we have to create a simple counter using javascript. For that create an HTML file and use a javascript function that displays the output.
Solution
- Create HTML file
- Use div tag and in that create box border <div style=” width: 400px; border: 15px solid grey; padding: 50px; margin: 50px;”>
- Enter suitable heading in tag <h1>Simple counter using javascript</h1>
- Add buttons which onclick the increament and decreament type <button onclick=”increase()”>+</button> , <button onclick=”decrease()”>-</button>
- Use CSS tag to design output
- In javascript initialize the variable data var data = 0;
- Printing default value of data that is h2 tag document.getElementById(“counting”).innerText = data;
- Add creation of increase function function increase() {
data = data + 1;
document.getElementById(“counting”).innerText = data;
- Add creation of decrease function function decrease() {
data = data – 1;
document.getElementById(“counting”).innerText = data;
}
JavaScript code to create simple counter using js function
<!DOCTYPE html> <html> <head> <title>Simple counter using js</title> </head> <body> <div =container> <div style=" width: 400px; border: 15px solid grey; padding: 50px; margin: 50px;"> <h1>Simple counter using javascript</h1> <button onclick="increase()">+</button> <h2 id="counting"></h2> <button onclick="decrease()">-</button> </div> <script> var data = 0; document.getElementById("counting").innerText = data; function increase() { data = data + 1; document.getElementById("counting").innerText = data; } function decrease() { data = data - 1; document.getElementById("counting").innerText = data; } </script> <style> body { position: absolute; left: 0%; text-align: center; } .container { justify-content: center; align-items: center; display: flex; height: 100%; text-align: center; } button { width: 60px; height: 40px; font-size: 20px; background-color: darkgray; color: honeydew; } button:hover { background-color: darkblue; color: grey; } h2 { color: black; margin: 0 30px; font-size: 25px; } h1 { font-size: 20px; color: grey; text-align: center; padding-left: 10%; } </style> </body> </html>
Output
In this way we will learn how to create simple counter using javascript.