Counter Example: Vanilla JavaScript
Gabor Szabo
Posted on January 3, 2023
This code is part of the counter example project. If you are looking for the buzz-words for this project then this is a Single Page Application implemented using HTML5 and Vanilla JavaScript.
It has two buttons.
- One of them is a counter. Every time you click on it the value on it will increase by one.
- The other one is a reset button.
<button id="counter">0</button>
<button id="reset">Reset</button>
<script>
function increment_counter() {
let counter = document.getElementById('counter').innerHTML;
counter++;
console.log(counter);
document.getElementById('counter').innerHTML = counter;
}
function reset_counter() {
console.log('reset');
document.getElementById('counter').innerHTML = 0;
}
document.getElementById('counter').addEventListener('click', increment_counter);
document.getElementById('reset').addEventListener('click', reset_counter);
</script>
In this little animated gif you can see the two small buttons at the top and most of the view is taken up by the console where you can see the console.log
messages.
At the top of the file we have two HTML buttons. Both have IDs for easier identification.
The JavaScript code has two functions and then two calls to document.getElementById
. These two calls will locate the HTML element with the ID given as a parameter and then connect a function to the "click" event of each one of them. These are the two functions we have.
This means that when the user clicks on the HTML element with the ID counter
the function increment_counter
will be executed and when the user clicks on the element with the ID reset
the reset_counter
function will be called.
Reset counter
The reset_counter
function is the easier to explain:
console.log('reset');
Is only there so we can see on the console of the browser that something happened.
Then we use the call
document.getElementById('counter')
to locate the HTML element and innerHTML
to set the content of the element to 0.
Increment counter
Here we first copy the content of the HTML element to a variable we cleverly named counter
.
Then we increment it by one using the ++
operator.
Then we have the console.log
call. Just so we can see in the console what's happening.
Finally we write back the value the HTML document.
Issues
Keeping our data (the counter) as part of the HTML is probably not a very good idea in a project more complex than this one. However, in this case it has the advantage that we don't need to think how we keep our data (which is normally in JavaScript) in sync with the display (which is the HTML).
This counter is also not persistent. If you reload the page the counter will be reset.
Posted on January 3, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
March 26, 2023
June 12, 2021