Search code examples
javascriptprojectcalculator

Calculator project - stuck - javascript


I am stuck at making this calculator work... so basically my calculator works if I press equals key, ( 1 + 2 = 3)... But I would like to make it work even when the user is pressing only operators, like 1+4/5+2, so that it calculates automatically even when pressing just operators.

This is my code:

// DOM elements 
const numberButton = document.querySelectorAll('.number');
const operatorButton = document.querySelectorAll('.operator');
const clearButton = document.querySelector('.clear');
const deleteButton = document.querySelector('.delete')
const showResult = document.querySelector('.result');
const currentOperand = document.querySelector('.current-operand');
const previousOperand = document.querySelector('.previous-operand');
const equalsKey = document.querySelector('.equals-key');

currentOperand.textContent = ' ';
previousOperand.textContent = ' ';

// Sum of a, b ... 
function add(a, b) {
  return a + b;
};

// Subtraction of a and b ...
function subtract(a, b) {
  return a - b;
};

// Multiply a, b ... 
function multiply(a, b) {
  return a * b;
};

// Divide a,b ... 
function divide(a, b) {
  return a / b;
};

// Create a new function operate that takes an operator and 2 numbers and then calls one of the above functions on the numbers.
function operate(num1, num2, operator) {
  switch (operator) {
    case "+":
      return add(num1, num2);
    case "-":
      return subtract(num1, num2);
    case "*":
      return multiply(num1, num2);
    case "/":
      return divide(num1, num2);
  }
};

//Create the functions that populate the display when you click the 
//number buttons… you should be storing the ‘display value’ in a variable somewhere 
//for use in the next step.

let storedNumber = '';
let clickedOperator = ''
let firstNumber = '';
let result = '';
currentOperand.textContent = 0;


numberButton.forEach((number) => {
  number.addEventListener('click', function() {
    storedNumber += number.value;
    currentOperand.textContent = storedNumber;
  })
});

operatorButton.forEach((operator => {
  operator.addEventListener('click', function() {

    // save the first number
    firstNumber = storedNumber;

    // get the operator that was clicked
    clickedOperator = operator.textContent;
    previousOperand.textContent = storedNumber + clickedOperator;
    storedNumber = '';

    console.log('FirstNumber' + firstNumber + 'Stored' + storedNumber)
    console.log(clickedOperator);

  })
}));

equalsKey.addEventListener('click', function() {
  // when equals key is clicked call operate() function
  result = operate(parseFloat(firstNumber), parseFloat(storedNumber), clickedOperator)
  // update content of current operation with result and previous operand with the calculation, make storedNumber = result
  currentOperand.textContent = result;
  previousOperand.textContent = firstNumber + ' ' + clickedOperator + ' ' + storedNumber;
  storedNumber = result;
  console.log('FirstNumber' + firstNumber + 'Stored' + storedNumber)
})
*,
*::before,
*::after {
  box-sizing: border-box;
  font-weight: normal;
}

body {
  margin: 0;
  padding: 0;
  background: linear-gradient(0.25turn, #3f87a6, #ebf8e1, #f69d3c);
  font-family: sans-serif;
}

.calculator-container {
  display: grid;
  justify-content: center;
  align-content: center;
  min-height: 100vh;
  grid-template-columns: repeat(4, 100px);
  grid-template-rows: minmax(120px, auto) repeat(5, 100px);
}

.two-cols {
  grid-column: span 2;
}

.calculator-container>button {
  cursor: pointer;
  font-size: 2rem;
  border: 1px solid #4289a7;
  outline: none;
  background-color: #f69d3c;
  opacity: 80%;
  border-radius: 5px;
}

.calculator-container>button:hover {
  opacity: 100%;
}

.calculator-display {
  grid-column: 1 / -1;
}

.calculator-display {
  background-color: #efd7a5;
  border: 1px solid #4289a7;
  opacity: 80%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  padding: 10px;
  padding-top: 39px;
  padding-bottom: 5px;
  border-radius: 5px;
}

.calculator-display .previous-operand {
  font-size: 1.5rem;
}

.calculator-display .current-operand {
  font-size: 2.5rem;
  padding-top: 7px;
}
!
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Calculator Odin Project</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="/style.css">
</head>

<body>
  <!--Create a basic HTML calculator with buttons for each digit, each of the above functions and an “Equals” key.
        
            Do not worry about wiring up the JS just yet.
            There should also be a display for the calculator, go ahead and fill it with some dummy numbers so you can get it looking right.
            Add a “clear” button.
        -->

  <div class="calculator-container">
    <div class="calculator-display">
      <div class="previous-operand">3214</div>
      <div class="current-operand">324324</div>
    </div>

    <button class="two-cols clear">AC</button>
    <button class="delete">DEL</button>
    <button class="operator">/</button>
    <button class="number" value="1">1</button>
    <button class="number" value="2">2</button>
    <button class="number" value="3">3</button>
    <button class="operator">*</button>
    <button class="number" value="4">4</button>
    <button class="number" value="5">5</button>
    <button class="number" value="6">6</button>
    <button class="operator">+</button>
    <button class="number" value="7">7</button>
    <button class="number" value="8">8</button>
    <button class="number" value="9">9</button>
    <button class="operator">-</button>
    <button class="number">.</button>
    <button class="number" value="0">0</button>
    <button class="equals-key two-cols result">=</button>

  </div>

  <script src="/index.js" async defer></script>
</body>

</html>


<!--Create a basic HTML calculator with buttons for each digit, each of the above functions and an “Equals” key.

    Do not worry about wiring up the JS just yet.
    There should also be a display for the calculator, go ahead and fill it with some dummy numbers so you can get it looking right.
    Add a “clear” button.
-->


Solution

  • Simply run the calculation each time a number is pressed, then update the view.

    For example, if you press '1' followed by '+' and then '2', the calculator will automatically display '3'.

    You can also make it compute the values when clicking an operator button, thought it might not make as much sense.

    // DOM elements 
    const numberButton = document.querySelectorAll('.number');
    const operatorButton = document.querySelectorAll('.operator');
    const clearButton = document.querySelector('.clear');
    const deleteButton = document.querySelector('.delete')
    const showResult = document.querySelector('.result');
    const currentOperand = document.querySelector('.current-operand');
    const previousOperand = document.querySelector('.previous-operand');
    const equalsKey = document.querySelector('.equals-key');
    
    currentOperand.textContent = ' ';
    previousOperand.textContent = ' ';
    
    // Sum of a, b ... 
    function add(a, b) {
      return a + b;
    };
    
    // Subtraction of a and b ...
    function subtract(a, b) {
      return a - b;
    };
    
    // Multiply a, b ... 
    function multiply(a, b) {
      return a * b;
    };
    
    // Divide a,b ... 
    function divide(a, b) {
      return a / b;
    };
    
    // Create a new function operate that takes an operator and 2 numbers and then calls one of the above functions on the numbers.
    function operate(num1, num2, operator) {
      switch (operator) {
        case "+":
          return add(num1, num2);
        case "-":
          return subtract(num1, num2);
        case "*":
          return multiply(num1, num2);
        case "/":
          return divide(num1, num2);
      }
    };
    
    //Create the functions that populate the display when you click the 
    //number buttons… you should be storing the ‘display value’ in a variable somewhere 
    //for use in the next step.
    
    let storedNumber = '';
    let clickedOperator = ''
    let firstNumber = '';
    let result = '';
    currentOperand.textContent = 0;
    
    
    numberButton.forEach((number) => {
      number.addEventListener('click', function() {
        storedNumber += number.value;
        previousOperand.textContent += storedNumber;
        calculate();
      })
    });
    
    operatorButton.forEach((operator => {
      operator.addEventListener('click', function() {
    
        // save the first number
        firstNumber = storedNumber;
    
        // get the operator that was clicked
        clickedOperator = operator.textContent;
        previousOperand.textContent = storedNumber + clickedOperator;
        storedNumber = '';
    
        console.log('FirstNumber' + firstNumber + 'Stored' + storedNumber)
        console.log(clickedOperator);
    
      })
    }));
    
    const calculate = () => {
      const result = operate(parseFloat(firstNumber), parseFloat(storedNumber), clickedOperator);
    
      currentOperand.textContent = result;
      }
    
    equalsKey.addEventListener('click', calculate);
    *,
    *::before,
    *::after {
      box-sizing: border-box;
      font-weight: normal;
    }
    
    body {
      margin: 0;
      padding: 0;
      background: linear-gradient(0.25turn, #3f87a6, #ebf8e1, #f69d3c);
      font-family: sans-serif;
    }
    
    .calculator-container {
      display: grid;
      justify-content: center;
      align-content: center;
      min-height: 100vh;
      grid-template-columns: repeat(4, 100px);
      grid-template-rows: minmax(120px, auto) repeat(5, 100px);
    }
    
    .two-cols {
      grid-column: span 2;
    }
    
    .calculator-container>button {
      cursor: pointer;
      font-size: 2rem;
      border: 1px solid #4289a7;
      outline: none;
      background-color: #f69d3c;
      opacity: 80%;
      border-radius: 5px;
    }
    
    .calculator-container>button:hover {
      opacity: 100%;
    }
    
    .calculator-display {
      grid-column: 1 / -1;
    }
    
    .calculator-display {
      background-color: #efd7a5;
      border: 1px solid #4289a7;
      opacity: 80%;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      padding: 10px;
      padding-top: 39px;
      padding-bottom: 5px;
      border-radius: 5px;
    }
    
    .calculator-display .previous-operand {
      font-size: 1.5rem;
    }
    
    .calculator-display .current-operand {
      font-size: 2.5rem;
      padding-top: 7px;
    }
    !
    <!DOCTYPE html>
    <!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
    <!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
    <!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
    <!--[if gt IE 8]><!-->
    <html class="no-js">
    <!--<![endif]-->
    
    <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>Calculator Odin Project</title>
      <meta name="description" content="">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="/style.css">
    </head>
    
    <body>
      <!--Create a basic HTML calculator with buttons for each digit, each of the above functions and an “Equals” key.
            
                Do not worry about wiring up the JS just yet.
                There should also be a display for the calculator, go ahead and fill it with some dummy numbers so you can get it looking right.
                Add a “clear” button.
            -->
    
      <div class="calculator-container">
        <div class="calculator-display">
          <div class="previous-operand">3214</div>
          <div class="current-operand">324324</div>
        </div>
    
        <button class="two-cols clear">AC</button>
        <button class="delete">DEL</button>
        <button class="operator">/</button>
        <button class="number" value="1">1</button>
        <button class="number" value="2">2</button>
        <button class="number" value="3">3</button>
        <button class="operator">*</button>
        <button class="number" value="4">4</button>
        <button class="number" value="5">5</button>
        <button class="number" value="6">6</button>
        <button class="operator">+</button>
        <button class="number" value="7">7</button>
        <button class="number" value="8">8</button>
        <button class="number" value="9">9</button>
        <button class="operator">-</button>
        <button class="number">.</button>
        <button class="number" value="0">0</button>
        <button class="equals-key two-cols result">=</button>
    
      </div>
    
      <script src="/index.js" async defer></script>
    </body>
    
    </html>
    
    
    <!--Create a basic HTML calculator with buttons for each digit, each of the above functions and an “Equals” key.
    
        Do not worry about wiring up the JS just yet.
        There should also be a display for the calculator, go ahead and fill it with some dummy numbers so you can get it looking right.
        Add a “clear” button.
    -->