I am currently trying to add 2 functionalities for a calculator project:
-
When a number button is clicked it will display on the calculator gui
-
to add that value into the variable "num".
In the GetNumber function, when I click a button this line successfully outputs that number onto the calculator for step 1.
outputBox.textContent += e.target.classList[1]
What I am struggling with is getting a return value of "num". I do the same thing here which works fine and correctly outputs the numbers when I console.log(num) however when I try to return "num" nothing comes back.
num += e.target.classList[1]
Codepen here for reference. I am testing it with the equals function so that when the equals button is clicked on the calculator, if working properly, it should output the numbers into the console.
HTML
<!DOCTYPE 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">
<title>Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calcContainer">
<div id="outputBox">
</div>
<div class="buttons">
<button class="number 7">7</button>
<button class="number 8">8</button>
<button class="number 9">9</button>
<button class="operator ÷">÷</button>
<button class="number 4">4</button>
<button class="number 5">5</button>
<button class="number 6">6</button>
<button class="operator x">x</button>
<button class="number 1">1</button>
<button class="number 2">2</button>
<button class="number 3">3</button>
<button class="operator -">-</button>
<button class="number 0">0</button>
<button id="clear">AC</button>
<button id="equals">=</button>
<button class="operator +">+</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
JS
let outputBox = document.getElementById("outputBox");
const number = document.getElementsByClassName("number");
const operator = document.getElementsByClassName("operator");
const equalsButton = document.getElementById("equals")
let a = "", middle = "", b = "", runningTotal = 0
function getNumber(num) {
for (let i = 0; i < number.length; i++) {
number[i].addEventListener("click", (e) => {
outputBox.textContent += e.target.classList[1]
num += e.target.classList[1]
console.log(num)
})
}
return num
}
a = getNumber(a)
function equals(abc) {
equalsButton.addEventListener("click", () => {
console.log(abc)
})
}
equals(a)
2
Answers
Here is a new code with fix to your issue.
Maybe you can try this approach?