Home > Enterprise >  Add Javascript counters to colour counter
Add Javascript counters to colour counter

Time:02-12

I am making a colour counter application, That has has 6 different colours.

I am currently trying to implement a pure JavaScript counter that has a individual counter for each colour.

(Correction: It is not to count the different colours displayed on the page, but when the user sees a colour in their surrounding environment that matches one of the 6 colours, they increase the counter by 1, for example the user sees the sky is blue and the grass is green, The user hovers over the blue colour, the increase and decrease buttons appear, the user increases the blue colour by 1 increment, Then for the grass the user hovers over the green colour, again the button appears and the user increases the green counter by 1.)

When a user hovers over the colour buttons must appear to increase or decrease the counter by 1, to a minimum of 0.

The count of each colour must always be displayed above the colour.

My current method seems rather long I'm sure there is a way to set up some sort of a method to handle all colours but again to have separate counters for each colour.

Please see the below image for what I am trying to achieve: See this image

Any help would be appreciated, I have included my current code below for reference

var green = 0;
var countEl1 = document.getElementById("green");
function plus1(){
    green  ;
    countEl1.value = green;
}
function minus1(){
    if (green > 0) {
        green--;
        countEl1.value = green;
    }
}
var brown = 0;
var countEl2 = document.getElementById("brown");
function plus2(){
    brown  ;
    countEl2.value = brown;
}
function minus2(){
    if (brown > 0) {
        brown--;
        countEl2.value = brown;
    }
}
var blue = 0;
var countEl3 = document.getElementById("blue");
function plus3(){
    blue  ;
    countEl3.value = blue;
}
function minus3(){
    if (blue > 0) {
        blue--;
        countEl3.value = blue;
    }
}
var yellow = 0;
var countEl4 = document.getElementById("yellow");
function plus4(){
    yellow  ;
    countEl4.value = yellow;
}
function minus4(){
    if (yellow > 0) {
        yellow--;
        countEl4.value = yellow;
    }
}
var gold = 0;
var countEl5 = document.getElementById("gold");
function plus5(){
    gold  ;
    countEl5.value = gold;
}
function minus5(){
    if (gold > 0) {
        gold--;
        countEl5.value = gold;
    }
}
var red = 0;
var countEl6 = document.getElementById("red");
function plus6(){
    red  ;
    countEl6.value = red;
}
function minus6(){
    if (red > 0) {
        red--;
        countEl6.value = red;
    }
}
.pyramid {
    clip-path: polygon(50% 0, 100% 100%, 0 100%);
    width: 100vmin;
    aspect-ratio: 9 / 15; /* 2/1 */
    background-color: white;
    display: grid;
    grid-template-columns: 1fr;

}
.pyramid > * {
    background: white;
}
.one {
    background-color: rgba(234, 27, 7, 0.97);
}
.two {
    background-color: rgba(244, 182, 0, 0.98);
    margin-top: 10px;
}
.three {
    background-color: rgba(249, 224, 41, 0.98);
    margin-top: 10px;
}
.four {
    background-color: rgba(4, 157, 252, 0.98);
}
.five {
    background-color: rgba(167, 118, 67, 0.99);
    gap: 0% !important;
}
.six {
    background-color: rgba(92, 213, 51, 0.98);
}
.counter input[type=button], input[type=text] {
    display: inline-block;
    width: 20px;
    background-color: transparent;
    outline: none;
    border: none;
    text-align: center;
    cursor: pointer;
    padding: 0px;
    color: black;
    height: 33px;
    font-family: 'Open Sans';
}
#container {
    width: 100px;
    height: 100px;
    position: relative;
}
#navi,
#infoi {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
#infoi {
    z-index: 10;
}
button {
    border-radius: 50%;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Colour counter</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/Main.js"></script>
</head>
<body>
<div id="container">
<h1>Colour counter</h1>
<div >
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
</div>

<h1>Counter Test</h1>
<div id="input_div">
    <input type="button" value="-" id="minus1" onclick="minus1()">
    <input type="text" size="25" value="0" id="green">
    <input type="button" value=" " id="plus1" onclick="plus1()">
    <script src="js/Main.js"></script>
</div>
<div id="input_div2">
    <input type="button" value="-" id="minus2" onclick="minus2()">
    <input type="text" size="25" value="0" id="brown">
    <input type="button" value=" " id="plus2" onclick="plus2()">
    <script src="js/Main.js"></script>
</div>




</div>
</body>
</html>

CodePudding user response:

Use an array from which do the operations on the DOM and apply map to do each colour's job, which would be to programatically attach the event listener to the DOM elements. Also, ensure the DOM has fully loaded before running your JS code:

window.onload = function() {

  let colours = ["green", "brown", "blue", "yellow", "gold", "red"]
    .map(id => {
      let colour = {
        elementCount: document.getElementById(id),
        elementPlus: document.getElementById(`${id}_plus`),
        elementMinus: document.getElementById(`${id}_minus`),
        counter: 0,
      };
    
      colour.elementPlus.addEventListener("click", function() {
        colour.counter  ;
        colour.elementCount.value = colour.counter;
      });
    
      colour.elementMinus.addEventListener("click", function() {
        if (colour.counter > 0) {
          colour.counter--;
          colour.elementCount.value = colour.counter;
        }
      });
    
      return colour;
    });

};

Adapt the HTML so the IDs match the ones used in the JS:

  • Instead of minus1, use green_minus. Do the same for the rest of minus buttons.
  • Instead of plus1, use green_minus. Do the same for the rest of plus buttons.

Adapt the HTML removing the onClick attribute (it is now assigned programatically using JS).

As a plus, now you have the colours variable, where all the DOM elements and each colour counter are stored for further inspection and or modification.

As an example, one colour in the HTML would be like:

<div id="input_div">
    <input type="button" value="-" id="green_minus">
    <input type="text" size="25" value="0" id="green">
    <input type="button" value=" " id="green_plus">
</div>
<!-- Other colours... -->
<script src="js/Main.js"></script>

window.onload = function() {

  let colours = ["green", "brown", "blue", "yellow", "gold", "red"]
    .map(id => {
      let colour = {
        elementCount: document.getElementById(id),
        elementPlus: document.getElementById(`${id}_plus`),
        elementMinus: document.getElementById(`${id}_minus`),
        counter: 0,
      };
    
      colour.elementPlus.addEventListener("click", function() {
        colour.counter  ;
        colour.elementCount.value = colour.counter;
      });
    
      colour.elementMinus.addEventListener("click", function() {
        if (colour.counter > 0) {
          colour.counter--;
          colour.elementCount.value = colour.counter;
        }
      });
    
      return colour;
    });
};
.pyramid {
    clip-path: polygon(50% 0, 100% 100%, 0 100%);
    width: 100vmin;
    aspect-ratio: 9 / 15; /* 2/1 */
    background-color: white;
    display: grid;
    grid-template-columns: 1fr;

}
.pyramid > * {
    background: white;
}
.one {
    background-color: rgba(234, 27, 7, 0.97);
}
.two {
    background-color: rgba(244, 182, 0, 0.98);
    margin-top: 10px;
}
.three {
    background-color: rgba(249, 224, 41, 0.98);
    margin-top: 10px;
}
.four {
    background-color: rgba(4, 157, 252, 0.98);
}
.five {
    background-color: rgba(167, 118, 67, 0.99);
    gap: 0% !important;
}
.six {
    background-color: rgba(92, 213, 51, 0.98);
}
.counter input[type=button], input[type=text] {
    display: inline-block;
    width: 20px;
    background-color: transparent;
    outline: none;
    border: none;
    text-align: center;
    cursor: pointer;
    padding: 0px;
    color: black;
    height: 33px;
    font-family: 'Open Sans';
}
#container {
    width: 100px;
    height: 100px;
    position: relative;
}
#navi,
#infoi {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
#infoi {
    z-index: 10;
}
button {
    border-radius: 50%;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Colour counter</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/Main.js"></script>
</head>
<body>
<div id="container">
<h1>Colour counter</h1>
<div >
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
</div>

<h1>Counter Test</h1>
<div id="input_div">
    <input type="button" value="-" id="green_minus">
    <input type="text" size="25" value="0" id="green">
    <input type="button" value=" " id="green_plus">
</div>
<div id="input_div2">
    <input type="button" value="-" id="brown_minus">
    <input type="text" size="25" value="0" id="brown">
    <input type="button" value=" " id="brown_plus">
</div>
<div id="input_div3">
    <input type="button" value="-" id="blue_minus">
    <input type="text" size="25" value="0" id="blue">
    <input type="button" value=" " id="blue_plus">
</div>
<div id="input_div4">
    <input type="button" value="-" id="yellow_minus">
    <input type="text" size="25" value="0" id="yellow">
    <input type="button" value=" " id="yellow_plus">
</div>
<div id="input_div5">
    <input type="button" value="-" id="gold_minus">
    <input type="text" size="25" value="0" id="gold">
    <input type="button" value=" " id="gold_plus">
</div>
<div id="input_div6">
    <input type="button" value="-" id="red_minus">
    <input type="text" size="25" value="0" id="red">
    <input type="button" value=" " id="red_plus">
</div>



</div>
</body>
</html>

CodePudding user response:

I have made a variaton adding dinamically colors using an input so you can call any color name you want.

Put the buttons above each color is kinda dificult because you are using a polygon, so in this example the button are in the left side

    <!DOCTYPE html>
    <html lang="en">

    <head>
      <meta charset="UTF-8">
      <title>Colour counter</title>
      <link rel="stylesheet" href="css/style.css">
      <script src="js/Main.js"></script>

      <style>
        .grid {
          display: flex;
          text-align: center;
          max-width: 480px;
        }

        .grid .counter {
          margin-right: 15px;
        }

        .counter .column {
          text-align: center;
          vertical-align: middle;
        }

        .column {
          height: 100px;
          width: 100px;
          display: flex;
          align-content: center;
          justify-content: center;
          align-items: center;
        }

        .form {
          margin: 10px 0;
        }

        .form input[type='text'] {
          margin: 3px 0;
          border: 1px solid black;
          width: 200px;
        }

        input[type='button'] {
          border: 1px solid black;
          margin: 0 4px;
        }

        .pyramid {
          clip-path: polygon(50% 0, 100% 100%, 0 100%);
          width: 300px;
          aspect-ratio: 9 / 15;
          /* 2/1 */
          background-color: white;
          display: grid;
          grid-template-columns: 1fr;

        }

        .pyramid>* {
          background: white;
        }

        .counter input[type=button],
        input[type=text] {
          display: inline-block;
          width: 20px;
          background-color: transparent;
          outline: none;
          border: none;
          text-align: center;
          cursor: pointer;
          padding: 0px;
          color: black;
          height: 33px;
          font-family: 'Open Sans';
        }

        #container {
          width: 100px;
          height: 100px;
          position: relative;
        }

        button {
          border-radius: 50%;
        }
      </style>



    </head>

    <body>
      <div >
        <h1>Colour counter</h1>
      </div>

      <div >
        <form>
          <label for="fcolour">Enter the colour name: </label>
          <br>
          <input id="fcolour" type="text" name="fcolour">
          <br>
          <input type="button" value="Submit">
        </form>
      </div>

      <div id="container">

        <div >
          <div >
          </div>
          <div >
          </div>
        </div>

      </div>

      <script>

        document.querySelector('form input[type="button"]').addEventListener('click', function (e) {
          var colCounter = document.querySelector('.grid .counter')
          var colPyramid = document.querySelector('.grid .pyramid')
          var colorName = document.getElementById('fcolour').value

          var newCounterChild = document.createElement('div')
          newCounterChild.classList.add('column')
          newCounterChild.innerHTML = `
            <input type="button" value="-" id="minus_${colorName}">
            <input type="text" size="25" value="0" id=counter_${colorName}>
            <input type="button" value=" " id="plus_${colorName}">
          `

          colCounter.appendChild(newCounterChild)

          var newPyramidChild = document.createElement('div')
          newPyramidChild.classList.add('column')
          newPyramidChild.style.backgroundColor = colorName
          newPyramidChild.style.marginTop = '10px'

          colPyramid.appendChild(newPyramidChild)

          document.getElementById(`plus_${colorName}`).addEventListener('click', function (v) {
            document.getElementById(`counter_${colorName}`).value  
          })

          document.getElementById(`minus_${colorName}`).addEventListener('click', function (v) {
            var val = document.getElementById(`counter_${colorName}`)
            val.value > 0 ? val.value-- : null
          })

        })

      </script>

    </body>

  • Related