JavaScript how to make a counter
Learn how to create a counter in Javascript with an example. Create a simple function that counts up with each click of a button.
Creating a Counter with JavaScript
A counter is a simple way to keep track of numbers in JavaScript. In this tutorial, we'll show you how to create a counter that starts at 0 and increases by 1 each time a button is clicked.
First, let's create the HTML element that will hold the counter. We'll use a <div>
element with an id of "counter":
<div id="counter"></div>
Next, let's create a JavaScript variable to hold the value of the counter. We'll call it "count", and set it to 0:
let count = 0;
Now, let's create a function that will update the counter when the button is clicked. We'll call it "updateCounter":
function updateCounter() {
// increment the counter by 1
count++;
// update the HTML element with the new value
document.getElementById('counter').innerHTML = count;
}
Finally, let's call this function when the button is clicked. We'll add an event listener to the button that calls the function:
// get the button element
const button = document.getElementById('button');
// add an event listener to the button
button.addEventListener('click', updateCounter);
Now, when the button is clicked, the counter will be incremented by 1 and the HTML element will be updated with the new value. Congratulations, you've created a counter with JavaScript!