Exercise: Click Counter
Note: We will use the same HTML page we have been using. I'll refer to it as clicker.html
.
In this section, we'll make a simple page that has a button and a counter. Each time the button is clicked, the value of the counter is incremented. We'll use the same page we have been using before.
Set up the html file
Set up the html file such its body contains at least the following two items:
a button with an id
a text element of your choice also with an id
An example is below:
You can have other elements and other styling to make it nicer, but that is up to you.
The script
Adding an event listener
Add an event listener to the script.js
file that listens for the DOM content to be loaded, upon which it adds an event listener to the button. Here's how that looks:
updateCounter
is the function that we will use to update the counter on the page.
updateCounter
function
updateCounter
functionInside this function we need to do the following:
Get the counter element from the page
Get its text value
Increment it by 1
Set the counter element's inner value to the new value
Try doing this yourself before looking at the code below.
Note that an element's inner text is always returned as a string, so you need to convert it to an integer. This can be done with the parseInt
function:
Test it out
That's all we had to do. Now, test out the code by saving all files, reloading the page, and then clicking the button. The counter value should get incrememented:
Bonus (try it yourself)
Try adding the following features:
When the counter value reaches a non-zero multiple of 10, its font color should change to gold, and set back to original color otherwise
Add a second button that resets the counter variable to 0
Add a third button that decrements the counter, but no longer decreases after reaching 0.
A sample solution can be found here.
Next steps
Next we'll look at how elements can be created or removed in a page.
Last updated