0

I'm writing code for a simple calculator but I'm not sure how to have it compute arithmetic operations (multiplication, adding, subtraction, division). So far, here's what I have:

      screen = document.querySelector('.answer'),
      panel = document.querySelector('.main-card'),
      number = document.querySelectorAll('.number'),
      operation = document.querySelectorAll('.function-btn')
      

number.forEach(function(item) {
  item.addEventListener('click', function(e) {
    let button = e.target.textContent;

    if(button) {
      screen.innerHTML += button
    }
  })
})

operation.forEach(function(item) {
  item.addEventListener('click', function(e) {
    let button = e.target.textContent;

    if(button && screen.innerHTML != '') {
      screen.innerHTML += button;
    }

    
  })
})

And here's my HTML:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="index.css">
  <title>Document</title>
</head>
<body>
  <div class="container">
    <div class="main-card">
      <div class="answer-bar">
        <h1 class="answer"></h1>
      </div>
      <div class="function-btn">
        <h1 class="multiply">x</h1>
        </div>
      <div class="function-btn">
        <h1 class="add">+</h1>
      </div>
      <div class="function-btn">
        <h1 class="subtract">-</h1>
      </div>
      <div class="function-btn">
        <h1 class="divide">/</h1>
      </div>
      <div class="function-btn">
        <h1 class="clear">C</h1>
      </div>
      <div class="number-buttons-1">
        <h1 class="number">1</h1>
        <h1 class="number">2</h1>
        <h1 class="number">3</h1>
      </div>
      <div class="number-buttons-2">
        <h1 class="number">4</h1>
        <h1 class="number">5</h1>
        <h1 class="number">6</h1>
      </div>
      <div class="number-buttons-3">
        <h1 class="number">7</h1>
        <h1 class="number">8</h1>
        <h1 class="number">9</h1>
      </div>
      <div class="equal">
        <h1>=</h1>
      </div>
      </div>
    </div>

  <script src="js.js"></script>
</body>
</html>

I've looked up some answers (for example, using eval) but I hear that you're not supposed to use that (even if this project won't be going up on a website). Is there a simple way to have the equals button compute what is on the screen? I've seen a lot of other code that just seems way too complex.

Andrew
  • 7
  • 2
  • you are going to need a master array that keeps track of every button pressed and what order they are pressed. once the equal sign is pressed, you will step through the array and try to turn it into a math problem. – Rick Aug 07 '21 at 18:33

0 Answers0