Home > Net >  How can I clear the first number on the display entered in a calculator so that the second number do
How can I clear the first number on the display entered in a calculator so that the second number do

Time:12-02

I'm creating a calculator using HTML, CSS, and JavaScript. I have one problem in my code. When a user clicks an operator after entering a number, the operator stays highlighted until the user enters the second number. The problem is, when the user enters the second number, the first number on the display does not disappear. So the second number gets concatenated to the first number. How can I solve this problem? When the user enters the second number, I want the display to clear the previous number and start displaying whatever the user is entering.

I have this in idea in pseudo code but don't know how to implement it because I don't know if pausing an element using JavaScript is possible:

After the operator is clicked, pause the display for the user but remove everything from the display under the hood. When the user clicks one of the digits, stop pausing the display and show everything to the user. By doing so, the first number would still be visible to the user while the operator is highlighted. However, once the user has started entering the second number, the display would display only the second number.

I'm trying to achieve something like this: https://mrbuddh4.github.io/calculator/ In this example, when a user clicks an operator, the number on the display does not disappear. When a digit is clicked after the operator, the previous number disappears and the display starts showing the current number being entered.

Show code snippet

// Basic math operations
function add(a, b) {
  return parseInt(a)   parseInt(b);
}

function subtract(a, b) {
  return parseInt(a) - parseInt(b);
}

function multiply(a, b) {
  return parseInt(a) * parseInt(b);
}

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

function operate(operator, a, b) {
  if (operator === " ") {
    return add(a, b);
  } else if (operator === "-") {
      return subtract(a, b);
  } else if (operator === "*") {
      return multiply(a, b);
  } else if (operator === "/") {
      return divide(a, b);
  }
}

function displayValue(e) {
  operators.forEach(operator => operator.classList.remove("active"));
  if (display.textContent === "0") {
    display.textContent = e.target.textContent;
  } else if (display.textContent !== "0") {
      display.textContent  = e.target.textContent;
      let paddingLeftValue = parseInt(window.getComputedStyle(display)
                                        .getPropertyValue("padding-left")) - 30;
      display.style.paddingLeft = `${paddingLeftValue}px`;
  }
}

function getValue() {
  if (firstDisplayValue) {
    secondDisplayValue = display.textContent;
    console.log(`second value: ${secondDisplayValue}`);
  } else {
      firstDisplayValue = display.textContent;
      console.log(`first value: ${firstDisplayValue}`);
  }
}

function getValueAndOp(e) {
  operators.forEach(operator => operator.classList.remove("active"));
  e.target.classList.add("active");
  getValue();
  if (e.target.getAttribute("id") === "divide") {
    operator = "/";
  } else if (e.target.getAttribute("id") === "multiply") {
      operator = "*";
  } else if (e.target.getAttribute("id") === "subtract") {
      operator = "-";
  } else if (e.target.getAttribute("id") === "add") {
      operator = " ";
  }
}

function calculate() {
  operators.forEach(operator => operator.classList.remove("active"));
  getValue();
  let solution = operate(operator, firstDisplayValue, secondDisplayValue);
  display.textContent = solution;
  let solutionLength = solution.toString().length;
  let paddingLeftValue = 440 - (solutionLength - 1) * 30;
  display.style.paddingLeft = `${paddingLeftValue}px`;
}

// Declare the main variables
let firstDisplayValue;
let secondDisplayValue;
let operator;

// Create the display variable
const display = document.querySelector(".display");

// Add event listeners to the digits
const buttons = document.querySelectorAll("#one, #two, #three, #four, #five,"   
                                " #six, #seven, #eight, #nine, #zero, #dot");
buttons.forEach(button => button.addEventListener("click", displayValue));

// Add event listeners to the operators
const operators = document.querySelectorAll(".operator");
operators.forEach(operator => operator.addEventListener("click", getValueAndOp));

// Add an event listener to =
const equal = document.querySelector("#equal");
equal.addEventListener("click", calculate);
* {
  box-sizing: border-box;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 97vh;
}

.calc {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  border: 5px solid black;
  border-radius: 25px;
  height: 660px;
  width: 500px;
  padding: 5px 0 5px 0;
  gap: 4px;
}

.calc>div {
  width: 480px;
}

.display {
  height: 130px;
  font-size: 60px;
  padding: 60px 0 0 440px;
}

.buttons {
  display: flex;
  flex-wrap: wrap;
  max-height: 470px;
  flex: auto;
  gap: 12px;
  padding: 8px 0 1px 8px;
}

.buttons>button {
  font-size: 40px;
  height: 75px;
  width: 107px;
  border-radius: 50%;
  background-color: rgb(231, 230, 230);
  border: none;
  transition: 4ms;
}

.clear {
  width: 345px !important;
  background-color: rgb(62, 198, 251) !important;
  color: white;
}

#zero {
  width: 225px !important;
}

.clear, #zero {
  border-radius: 50px !important;
}

.operator, #equal {
  background-color: rgb(6, 118, 223) !important;
  color: white !important;
}

button:active {
  background-color: rgb(163, 163, 163);
}

.clear:active {
  background-color: rgb(0, 162, 255) !important;
}

#equal:active {
  background-color: rgb(0, 0, 204) !important;
}

.active {
  background-color: rgb(0, 0, 204) !important;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Calculator</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="calc">
      <div class="display">0</div>
      <div class="buttons">
        <button class="clear">Clear</button>
        <button class="operator" id="divide">÷</button>
        <button id="seven">7</button>
        <button id="eight">8</button>
        <button id="nine">9</button>
        <button class="operator" id="multiply">×</button>
        <button id="four">4</button>
        <button id="five">5</button>
        <button id="six">6</button>
        <button class="operator" id="subtract"></button>
        <button id="one">1</button>
        <button id="two">2</button>
        <button id="three">3</button>
        <button class="operator" id="add"> </button>
        <button id="zero">0</button>
        <button id="dot">.</button>
        <button id="equal">=</button>
      </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

When the user enters the second number, I want the display to clear the previous number and start displaying whatever the user is entering.

So you just need to "remember" that a click on an operator button happened, so that you can react accordingly, when the next number button gets clicked.

Set a flag (clearDisplay or similar) to true, when one of the operator buttons gets clicked.
When one of the numbers gets clicked, check if that flag is set first, and if so, clear your display, before setting the flag to false again.

  • Related