
In this JavaScript tutorial we will create a simple counter with few buttons. On clicking the buttons, the value of counter will increase or decrease.
Create Counter with Few Buttons
Below code will create a region where the counter value will be displayed. And 4 buttons that will call a JavaScript function on click. On clicking these buttons the value of counter will increase or decrease.
We will also create a reset button.
<h3>Counter Value: <span id="counter-value">0</span></h3>
<button type="button" onclick="counterFunction(1)">Increase By one</button> <button type="button" onclick="counterFunction(-1)">Decrease By one</button>
<br /><br />
<button type="button" onclick="counterFunction(5)">Increase By Five</button> <button type="button" onclick="counterFunction(-5)">Decrease By Five</button>
<br /><br />
<button type="button" onclick="counterResetFunction()">Reset Counter</button>
JavaScript
let counter = 0;
const conterVal = document.querySelector("#counter-value");
// Increment Decrement function
function counterFunction(x) {
counter += x;
conterVal.innerHTML = counter;
}
// counter reset function
function counterResetFunction() {
counter = 0;
conterVal.innerHTML = counter;
}
Demo
Category
- JavaScript – Change Background Color to Any Random Colors on Button Click
- Counter with Increment and Decrement Buttons using VueJS