Counter

Project Description

An increment and decrement counter that changes the colour of the number displayed on the web page.

Setting up the base web page

Your first task is to set up the base web page.

  1. In your javascript/projects folder, create a new sub-folder named counter.
  2. Download the following file to this new javascript/projects/counter folder.   index.html
  3. Give it the filename index.html.
  4. Update the website logo, favicon, <title> tag and the <footer> with your own details.

This file contains all the necessary HTML and CSS for this project.

Adding the JavaScript code

At the bottom of your index.html web page, just before the closing </body> tag, add the following JavaScript code within a <script> tag.

// set inital value to zero
let count = 0;
// select value and buttons
const value = document.querySelector("#value");
const btns = document.querySelectorAll(".btn");

btns.forEach(function (btn) {
   btn.addEventListener("click", function (e) {
      const styles = e.currentTarget.classList;
      if (styles.contains("decrease")) {
         count--;
      } 
      else if (styles.contains("increase")) {
         count++;
      }
      else {
         count = 0;
      }

      if (count > 0) {
         value.style.color = "green";
      }
      if (count < 0) {
         value.style.color = "red";
      }
      if (count === 0) {
         value.style.color = "#222";
      }
      value.textContent = count;
   });
});

Save your file and verify it works correctly.