CrystalH
CrystalH

Reputation: 85

Push numbers into array on click event

I'm trying to build a calculator and at this point, need to "collect" any numbers that get clicked in an array. Right now I'm unsure of where to build that array (should it be in a different function all together?). I think I'll need to use .push(), but know I need to use it on an array and am not sure where to define that. When I console.log(gridItems), clearly I get everything, but only want the numbers...

/*Calculator 

function add(n, x) {
  return n + x;
}
console.log(add(3, 8));

function subtract(n, x) {
  return n - x;
}
console.log(subtract(3, 8));

function multiply(n, x) {
  return n * x;
}
console.log(multiply(3, 8));

function divide(n, x) {
  return n / x;
}
console.log(divide(3, 8));*/

// console.log number when button is clicked

function getValue(e){
  var divValue = parseInt(e.target.textContent);
    console.log(divValue);
   }

function numberTrack() {
  
  var gridItems = document.getElementsByClassName('grid');

  for (var i = 0; i < gridItems.length; i ++) {
      gridItems[i].onclick = getValue;
  }
}

numberTrack();
#grid-container {
  width: 200px;
}

.grid {
  width: 50px;
  height: 50px;
  display: inline-block;
  text-align: center;
}

.gray {
  background-color: #ccc;
}

.pink {
  background-color: pink;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <div id="grid-container" data-value="1">
    <div class="grid gray">0</div>
    <div class ="grid pink">1</div>
    <div class="grid gray">2</div>
    <div class ="grid pink">3</div>
    <div class="grid gray">4</div>
    <div class ="grid pink">5</div>
    <div class="grid gray">6</div>
    <div class ="grid pink">7</div>
    <div class="grid gray">8</div>
    <div class ="grid pink">9</div>
  </div>
  </head>
<body>

</body>
</html>

Upvotes: 0

Views: 3604

Answers (1)

Long Nguyen
Long Nguyen

Reputation: 11275

You can define it in global scope like this:

var clickedNumbers = []

function getValue(e) {
    var divValue = parseInt(e.target.textContent);
    clickedNumbers.push(divValue);
}

function numberTrack() {
    var gridItems = document.getElementsByClassName('grid');

    for (var i = 0; i < gridItems.length; i++) {
        gridItems[i].onclick = getValue;
    }
}

numberTrack();

Then push clicked number to array clickedNumbers by clickedNumbers.push(divValue)

Upvotes: 1

Related Questions