Counter

Page section: playground
0

Notes

This was an exercise from FreeCodeCamp’s beginner JS projects.

Here is the HTML:

<section id="counter">
    <span id="value">0</span>
    <div class="buttons">
        <button class="counter-btn decrease">decrease</button>
        <button class="counter-btn reset">reset</button>
        <button class="counter-btn increase">increase</button>
    </div>
</section>

A btns variable creates a node list which is an array like structure, ie. NOT an array. The forEach() array method works on this but not all array methods will.

const btns = document.querySelectorAll('.buttons button');

Using 1 event listener for 3 buttons

Rather than create a separate event listener for each button querySelectorAll() was used so a single event listener was added to all the buttons. These were then filtered using event target and then by which class each button was with classList.contains.

The event listener is added to all buttons in the .buttons div. Then a forEach() method is run on these, btns.forEach() using event target to find which button was pressed. Rather than e.target he used e.currentTarget instead. Both seem to work though.

Next if statements were used with contains..

const elClasses = e.currentTarget.classList;

if ( elClasses.contains('decrease')) {

contains() is a method of classList and because that is what elClasses is can be used in this context. See Traversy Media page on classList.contains.

const elClasses = e.currentTarget.classList

This was used to test whether a button that has been clicked had a specific class (decrease or increase classes).Those from the decrease clicks subtract 1 from the count variable, those with increase add 1 to it.

Multiple if statements. The last 3 could have been done with else if and else which was the first way I did it.