JS Calculator - what is wrong with my code? - javascript

EDIT 2: I'm just starting again from scratch. No point in trying to understand these complex problems problems right now when I am a novice. Have consulted someone from my cohort who can go through it with me. I appreciate the advice and insight.
I have been editing this code heavily, as the original relied a constructor. The calculator does not currently append any numbers to either displays when pushed, and I am not sure why! I think the problem lies somewhere in the appending/ node process or the update display function! Any and all advice/ ideas welcomed.
For context I am 5 weeks into a 12 week intensive course and am a baby baby baby coder. Please explain like I am 5!!!
EDIT: If you want to see original code please look at my previous question!
JAVA SCRIPT
const calculator =
(previousOperandTextElement, currentOperandTextElement, operation);
clear = () => {
currentOperand = "";
previousOperand = "";
operation = undefined;
};
remove = () => {
currentOperand = currentOperand.toString().slice(0, -1);
};
chooseOperation = (operation) => {
if (currentOperand === "") return;
if (previousOperand !== "") {
compute();
}
operation = operation;
previousOperand = currentOperand;
currentOperand = "";
};
compute = () => {
let computation;
const prev = parseFloat(previousOperand);
const current = parseFloat(currentOperand);
if (isNaN(prev) || isNaN(current)) return;
switch (operation) {
case "+":
computation = prev + current;
break;
case "-":
computation = prev - current;
break;
case "*":
computation = prev * current;
break;
case "÷":
computation = prev / current;
break;
default:
return;
}
currentOperand = computation;
operation = undefined;
previousOperand = "";
};
getDisplayNumber = (number) => {
const stringNumber = number.toString();
const integerDigits = parseFloat(stringNumber.split(".")[0]);
const decimalDigits = stringNumber.split(".")[1];
let integerDisplay;
if (isNaN(integerDigits)) {
integerDisplay = "";
} else {
integerDisplay = integerDigits.toLocaleString("en", {
maximumFractionDigits: 0,
});
}
if (decimalDigits != null) {
return `${integerDisplay}.${decimalDigits}`;
} else {
return integerDisplay;
}
};
updateDisplay = () => {
currentOperandTextElement.innerText = getDisplayNumber(currentOperand);
if (operation != null) {
previousOperandTextElement.innerText = `${getDisplayNumber(
previousOperand
)} ${operation}`;
} else {
previousOperandTextElement.innerText = "";
}
};
appendNumber = (number) => {
if (number === "." && currentOperand.includes(".")) return;
currentOperand = currentOperand.toString() + number.toString();
};
equalsButton.addEventListener("click", (button) => {
calculator.compute();
calculator.updateDisplay();
});
numberButtons.forEach = (button) => {
button.addEventListener("click", () => {
calculator.appendNumber(button.innerText);
calculator.updateDisplay();
});
};
operationButtons.forEach = (button) => {
button.addEventListener("click", () => {
calculator.chooseOperation(button.innerText);
calculator.updateDisplay();
});
};
allClearButton.addEventListener("click", (button) => {
calculator.clear();
calculator.updateDisplay();
});
deleteButton.addEventListener("click", (button) => {
calculator.delete();
calculator.updateDisplay();
});
item = (previousOperandTextElement, currentOperandTextElement) => {
previousOperandTextElement = previousOperandTextElement;
currentOperandTextElement = currentOperandTextElement;
clear();
};
const numberButtons = document.querySelectorAll("[data-number]");
const operationButtons = document.querySelectorAll("[data-operation]");
const equalsButton = document.querySelector("[data-equals]");
const deleteButton = document.querySelector("[data-delete]");
const allClearButton = document.querySelector("[data-all-clear]");
const previousOperandTextElement = document.querySelector(
"[data-previous-operand]"
);
const currentOperandTextElement = document.querySelector(
"[data-current-operand]"
);
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Calculator</title>
<script src="calcedit.js" defer></script>
</head>
<body>
<div class="calculator-grid">
<div class="output">
<div data-previous-operand class="previous-operand"></div>
<div data-current-operand class="current-operand"></div>
</div>
<button data-all-clear class="span-two">AC</button>
<button data-delete>DEL</button>
<button data-operation>÷</button>
<button data-number>1</button>
<button data-number>2</button>
<button data-number>3</button>
<button data-operation>x</button>
<button data-number>4</button>
<button data-number>5</button>
<button data-number>6</button>
<button data-operation>+</button>
<button data-number>7</button>
<button data-number>8</button>
<button data-number>9</button>
<button data-operation>-</button>
<button data-number>.</button>
<button data-number>0</button>
<button data-equals class="span-two">=</button>
</div>
</body>
</html>

So reading through your code, this issue is related to your understanding of your previous question
removing the Class means you no longer have a calculator instance or Object to work with so you can to work in a more procedural way
To start with
const calculator =
(previousOperandTextElement, currentOperandTextElement, operation);
Should be replaced with
var previousOperandTextElement = "",
currentOperandTextElement = "",
operation;
Anywhere you've got calculator for example calculator.compute(); should just be replaced with the new function you've created, in this case compute(); because you don't have a calculator object to work with.
As the previous comments suggested, for this may not be a good approach and a class / prototype approach might be better (what you had originally)

Related

Concat function not working or bad if then statement?

I'm making a calculator and ran into some issues with an if/else function giving me unexpected results. The logic seems kind of sound when I run it over so I would like some input on what I may have wrong here. The code is giving unexpected results from expressionMaker where it seems to clear the first "if --> if " statements but none of the else ones.
Edit: thanks for the feedback. I've narrowed the issue down to this portion.
else if ((EventTarget == numbers) && (expression.a > 0) && (expression.operand !== 0)) {
if (expression.b == 0) {
expression.b = keyValue
}
else {
expression.b = concat(expression.b, keyValue)
}
}
const btn = document.getElementById("calculatorGrid");
const display = document.getElementById("display");
const miniscreen = document.getElementById("miniScreen")
const equals = document.getElementById("evaluate")
const numbers = document.querySelectorAll(".Nbuttons");
const clear = document.getElementById("clear");
const add = document.getElementById("plus");
const sub = document.getElementById("subtract");
const multi = document.getElementById("multiply");
const divi = document.getElementById("divide");
const operators = document.querySelectorAll(".operators");
let nums = document.getElementById("nums")
numbers.values = nums.textContent
const calculate = (() => {
const add = (a, b) => a + b;
const sub = (a, b) => a - b;
const mul = (a, b) => a * b;
const div = (a, b) => a / b;
return {
add,
sub,
mul,
div,
};
});
const expression = {
a: 0,
operand: 0,
b: 0,
};
function expressionMaker(keyValue) {
const concat = (a, b) => {
return ("" + a + b)
};
if (EventTarget == numbers && expression.a == 0 || expression.operand == 0) {
if (expression.a == 0) {
expression.a = keyValue
}
else if (expression.a > 0) {
expression.a = concat(expression.a, keyValue)
}
display.innerHTML = expression.a
}
else if ((EventTarget == numbers) && (expression.a > 0) && (expression.operand !== 0)) {
if (expression.b == 0) {
expression.b = keyValue
}
else {
expression.b = concat(expression.b, keyValue)
}
}
else {
null
}
}
function evaluate() {
var result
if (expression.operand == "+") {
var result = calculate.add(expression.a, expression.b)
}
else if (expression.operand == "-") {
result = calculate.sub(expression.a, expression.b)
}
else if (expression.operand == "x") {
result = calculate.mul(expression.a, expression.b)
}
else if (expression.operand == "/") {
result = calculate.div(expression.a, expression.b)
}
else {
return null
}
display.innerHTML = result
return result
}
clear.addEventListener("click", () => {
clearOut()
})
equals.addEventListener("click", () => {
evaluate(expression.a, expression.b)
})
function setNums() {
let nums = document.getElementById("nums")
numbers.values = nums.textContent
};
setNums();
function clearOut() {
display.textContent = 0
expression.a = 0
expression.operand = 0
expression.b = 0
};
clear.addEventListener("click", function() {
clearOut();
});
add.addEventListener("click", () => {
expression.operand = "+"
display.innerHTML = "+"
})
sub.addEventListener("click", () => {
expression.operand = "-"
display.innerHTML = "-"
})
multi.addEventListener("click", () => {
expression.operand = "x"
display.innerHTML = "x"
})
divi.addEventListener("click", () => {
expression.operand = "/"
display.innerHTML = "/"
})
numbers.forEach(function(element) {
element.addEventListener("click", function(event) {
var key = event.target
let keyValue = key.textContent
expressionMaker(keyValue)
});
});
<!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 id="display">
<div id="miniScreen"></div>
</div>
<div id="calculatorGrid">
<button class="Nbuttons" id="nums" data-number="1">1</button>
<button class="Nbuttons" id="nums" data-number="2">2</button>
<button class="Nbuttons" id="nums" data-number="3">3</button>
<button class="Nbuttons" id="nums" data-number="4">4</button>
<button class="Nbuttons" id="nums" data-number="5">5</button>
<button class="Nbuttons" id="nums" data-number="6">6</button>
<button class="Nbuttons" id="nums" data-number="7">7</button>
<button class="Nbuttons" id="nums" data-number="8">8</button>
<button class="Nbuttons" id="nums" data-number="9">9</button>
<button class="Nbuttons" id="nums" data-number="0">0</button>
<button class="operators" id="plus" data-operator="+">+</button>
<button class="operators" id="subtract" data-operator="-">-</button>
<button class="operators" id="multiply" data-operator="*">x</button>
<button class="operators" id="divide" data-operator="/">÷</button>
<button id="clear">clear</button>
<button id="evaluate"> =</button>
</div>
<script src="script.js" defer></script>
</body>
</html>
Let's start with the beginning, you can replace this function, with 4 separate "addEventListener", it's going to be way less confusing and less error prone.
operators.forEach(function(element) {
element.addEventListener("click", function() {
if (EventTarget == add) {
expression.operand = "+"
display.innerHTML = "+"
}
else if (EventTarget == sub) {
expression.operand = "-"
display.innerHTML = "-"
}
else if (EventTarget == multi) {
expression.operand = "x"
display.innerHTML = "x"
}
else if (EventTarget == divi) {
expression.operand = "/"
display.innerHTML = "/"
}
})
})
New version:
add.addEventListener("click", function() {
expression.operand = "+";
display.innerHTML += "+";
});
sub.addEventListener("click", function() {
expression.operand = "-";
display.innerHTML += "-";
});
multi.addEventListener("click", function() {
expression.operand = "x";
display.innerHTML += "x";
});
divi.addEventListener("click", function() {
expression.operand = "/";
display.innerHTML += "/";
});
The thing with the "unexpected behavior" is that I'm not sure what your logic was trying to do, the only thing I can suggest you is take a look at this: https://developer.chrome.com/docs/devtools/javascript/ you'll debug a lot while coding, so it's always great to give it a try.
Using the developer tools, you'll be able to see the values in every variable at each step, that should make it easier for you to find where things are going south.
I hope the below answer is suitable for you.
may be your elements have duplicate id like id="nums"
you can also complete like this..
const miniscreen = document.getElementById("miniScreen");
function clearValue(){
miniscreen.innerHTML=0;
}
function mini(param){
if(miniscreen.innerHTML==0){
miniscreen.innerHTML=param;
}else{
miniscreen.innerHTML+=param;
}
}
function calculate(){
miniscreen.innerHTML=eval(miniscreen.innerHTML);
}
<body>
<div id="display">
<div id="miniScreen">0</div>
</div>
<div id="calculatorGrid">
<button class="Nbuttons" onclick="mini('1')" data-number="1">1</button>
<button class="Nbuttons" onclick="mini('2')" data-number="2">2</button>
<button class="Nbuttons" onclick="mini('3')" data-number="3">3</button>
<button class="Nbuttons" onclick="mini('4')">4</button>
<button class="Nbuttons" onclick="mini('5')">5</button>
<button class="Nbuttons" onclick="mini('6')">6</button>
<button class="Nbuttons" onclick="mini('7')">7</button>
<button class="Nbuttons" onclick="mini('8')">8</button>
<button class="Nbuttons" onclick="mini('9')">9</button>
<button class="Nbuttons" onclick="mini('0')">0</button>
<button class="operators" id="plus" onclick="mini('+')">+</button>
<button class="operators" id="subtract" onclick="mini('-')">-</button>
<button class="operators" id="multiply" onclick="mini('*')">x</button>
<button class="operators" id="divide" onclick="mini('/')">÷</button>
<button id="clear" onclick="clearValue()">clear</button>
<button id="evaluate" onclick="calculate()"> =</button>
</div>
</body>
Thank you.

I am trying to push a value onto an array with .push(), but it stops pushing values once the array length reaches two

I'm trying to create a javascript calculator for The Odin Project. I finally felt like I was making a bit of progress, after headbutting my keyboard for hours, and then this weird bug arose.
In the function where I add event listeners to the operator buttons, I am trying to push the current operator (the last one which was clicked) on to an array which keeps track of the operator buttons which have been clicked ('newOperators.push(e.target.innerText)').
If I spam the operator button, it pushes on to the array just fine. But when I am trying to chain together a series of operations, the newOperators.push() method seems to quit after the array length reaches two.
To test, I added another dummy array and pushed letters onto it on using another push() method, which I put on the line above newOperators.push(), and that seems to work just fine. I've tried switching newOperators.push() to newOperators.unshift() and that has the same issue.
Losing my mind here, any help would be much appreciated!
Javascript:
let display = document.querySelector('.display');
let title = document.querySelector('.title');
let plus = document.querySelector('.plus');
let minus = document.querySelector('.minus');
let times = document.querySelector('.multiply');
let divide = document.querySelector('.divide');
let equal = document.querySelector('.equal');
let period = document.querySelector('.period');
let one = document.querySelector('.one');
let two = document.querySelector('.two');
let three = document.querySelector('.three');
let four = document.querySelector('.four');
let five = document.querySelector('.five');
let six = document.querySelector('.six');
let seven = document.querySelector('.seven');
let eight = document.querySelector('.eight');
let nine = document.querySelector('.nine');
let nought = document.querySelector('.nought');
let buttons = document.querySelectorAll('button');
let operators = document.querySelectorAll('.operator');
let numbers = document.querySelectorAll('.number');
let currentCalc = [];
let currentOp = '';
let firstNumber = 0;
let secondNumber = 0;
let thirdNumber = 0;
let firstStash = 0;
let secondStash = 0;
let total = 0;
let calculated = false;
let newOperators = [];
const add = function(a,b) {
return a + b;
};
const subtract = function(a,b) {
return a - b;
};
const multiply = function(a,b) {
return a * b
};
const division = function(a,b) {
return a / b
};
function operate(fnum,snum, op) {
if(op === '+') {
let sum = add(fnum,snum);
return sum;
} else if(op === '-') {
let sum = subtract(fnum,snum);
return sum;
} else if(op === 'x') {
let sum = multiply(fnum,snum);
return sum;
} else if(op === '/') {
let sum = division(fnum,snum);
return sum;
}
}
let fNumArr = [];
let sNumArr = [];
let tNumArr = [];
numbers.forEach((e) => {
e.addEventListener('click', (e) => {
console.log('numberFunc', newOperators)
if(newOperators.length < 1) {
fNumArr.push(e.target.innerText)
firstNumber = parseInt(fNumArr.join(''));
console.log('first',firstNumber);
display.textContent = firstNumber;
} else if( newOperators.length = 1) {
sNumArr.push(e.target.innerText);
secondNumber = parseInt(sNumArr.join(''));
console.log('second',secondNumber);
display.textContent = secondNumber;
} else if(newOperators.length > 1) {
tNumArr.push(e.target.innerText);
thirdNumber = parseInt(tNumArr.join(''));
console.log('third',thirdNumber);
display.textContent = thirdNumber;
}
})
})
operators.forEach((e) => {
e.addEventListener('click', (e) => {
console.log(currentOp)
newOperators.push(e.target.innerText);
console.log('topOfOp',newOperators)
display.innerText = '';
if(newOperators.length === 1) {
} else if(newOperators.length === 2) {
console.log(operate(firstNumber,secondNumber,newOperators[1]));
total = operate(firstNumber,secondNumber,newOperators[1]);
display.innerText = total;
firstNumber = total;
secondNumber = 0;
fNumArr = [];
fNumArr.push(total)
sNumArr = [];
}
})
})
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>Caculator</title>
<link rel="stylesheet" href="styles.css">
<script src="./app.js" defer></script>
</head>
<body>
<h1 class="title">Calculator</h1>
<div class="container">
<div class="calculator">
<div class="display">This will print result</div>
<button class="clear">Clear</button>
<button class="plus operator">+</button>
<button class="minus operator">-</button>
<button class="multiply operator">x</button>
<button class="divide operator">/</button>
<button class="equal ">=</button>
<button class="one number">1</button>
<button class="two number">2</button>
<button class="three number">3</button>
<button class="four number">4</button>
<button class="five number">5</button>
<button class="six number">6</button>
<button class="seven number">7</button>
<button class="eight number">8</button>
<button class="nine number">9</button>
<button class="nought number">0</button>
<button class="period number">.</button>
</div>
</div>
</body>
</html>
In your numbers.forEach loop you made the mistake of:
if( newOperators.length = 1)
You should fix that.
Also, a little advice as you are starting out (I am also starting out WebDev):
You should name your variables clearly even of they are too long.
Refractor your code into functions and files for example make it so you pass in a callback to your event listeners and get rid of repetitive code. Remember keep it DRY (Don't Repeat Your code)

How do I simplify my code by making one addAndSubtract function?

Like the title says, I would like to simplify this JavaScript so that I have one addAndSubtract function for the buttons.
I am quite new and I have no idea how to go about it.
Here is the code:
let add= document.querySelector("#add");
let subtract = document.querySelector("#subtract");
add.addEventListener("click",function(){
let output = document.querySelector("#output");
let result = Number(output.innerText) + 1;
if (result >10){
result = 10;
}
output.innerText = result;
});
subtract.addEventListener("click",function(){
let output = document.querySelector("#output")
let result = Number(output.innerText) - 1;
if (result<0){
result=0;
}
output.innerText = result;
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script defer src="script.js"></script>
<title>Counter</title>
</head>
<body>
<h1>Le Count!</h1>
<div class = "Counter_Container">
<button id="subtract">-</button><span id="output">0</span><button id="add">+</button>
</div>
</body>
</html>
You can read the ID of the button being clicked in the handler, and act accordingly. (The switch could be a series of ifs too.)
function handleClick(event) {
const action = event.target.id;
const output = document.querySelector("#output");
let value = parseInt(output.innerText);
switch (action) {
case "add":
value++;
break;
case "subtract":
value--;
break;
}
value = Math.min(10, Math.max(value, 0)); // clamp to 0..10
output.innerText = value;
}
document.querySelector("#subtract").addEventListener("click", handleClick);
document.querySelector("#add").addEventListener("click", handleClick);
<h1>Le Count!</h1>
<div class="Counter_Container">
<button id="subtract">-</button><span id="output">0</span><button id="add">+</button>
</div>
Create a single function which takes your result number and add/subtract as parameter.
function eventer(result_param, arithmat){
let output = document.querySelector("#output")
if(arithmat){
let result = Number(output.innerText) + 1;
}else{
let result = Number(output.innerText) - 1;
}
if (result<result_param){
result=0;
}
}
Always try to make your similar code converted to reusable functions and if_else to ternary operators.
You need to create a function as following
function operation(val,maxvalue,minvalue){
let output = document.querySelector("#output")
let result = Number(output.innerText) + val;
if (result<minvalue){
result=minvalue;
}
if (result>maxvalue){
result=maxvalue;
}
output.innerText = result;
}
And use as below
let subtract = document.querySelector("#subtract");
subtract.addEventListener("click",operation.bind(this,-1,10,0))
let add = document.querySelector("#add");
add.addEventListener("click",operation.bind(this,1,10,0))
Let me know if you face any issue
Just add a data attribute to each button that describes the operation that should be performed. Use the same click handler and check the attribute for which operation should be performed.
It's also easier to keep track of the value in a scoped variable too.
let value = 0;
const output = document.querySelector("#output");
const buttons = document.querySelectorAll(".operation");
const operations = {
add: () => value = Math.min(++value, 10),
subtract: () => value = Math.max(--value, 0)
};
const setOutput = () => {
output.innerText = value;
};
// set initial output value
setOutput();
[...buttons].forEach((button) => {
button.addEventListener('click', (e) => {
const operation = e.target.dataset.operation;
let func = operations[operation];
func && func();
setOutput();
});
});
<h1>Le Count!</h1>
<div class="Counter_Container">
<button id="subtract" class="operation" data-operation="subtract">-</button>
<span id="output"></span>
<button id="add" class="operation" data-operation="add">+</button>
<button id="multiply" class="operation" data-operation="multiply">*</button>
</div>

What can I do to mix operations ? with vanilla javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm working on a simple calculator that implements a sum, rest, multiplication, and division.
I would like to take the inner text inside of any button with the class "number" to use it later like a number to pass through a function that does the math.
These are the functions to work with the calculator.
const add = (num1, num2) => {
return num1 + num2;
};
const subtract = (num1, num2) => {
return num1 - num2;
};
const multiply = (num1, num2) => {
return num1 * num2;
};
const divide = (num1, num2) => {
return num1 / num2;
};
// Our Buttons
const outPut = document.getElementById('output');
const num = document.getElementsByClassName('number');
const addBtn = document.querySelector('.addOperator');
const subtractBtn = document.querySelector('.subtractOperator');
const multiplyBtn = document.querySelector('.multiplyOperator');
const divideBtn = document.querySelector('.divideOperator');
const allClear = document.querySelector('.ac');
const equals = document.querySelector('.equals');
let plusFirsValue = '';
let secondValue = 0;
let subFirstValue = 0;
let multFirstValue = 0;
let divFirstValue = 0;
for(let i = 0; i < num.length; i++) {
num[i].addEventListener('click', () => {
outPut.innerText += num[i].innerText;
console.log(outPut.innerText);
});
};
addBtn.addEventListener('click', () => {
plusFirsValue = Number(outPut.innerText);
outPut.innerText = '';
console.log(plusFirsValue);
});
subtractBtn.addEventListener('click', () => {
subFirstValue = Number(outPut.innerText);
outPut.innerText = '';
console.log(plusFirsValue);
});
multiplyBtn.addEventListener('click', () => {
multFirstValue = Number(outPut.innerText);
outPut.innerText = '';
});
divideBtn.addEventListener('click', () => {
divFirstValue = Number(outPut.innerText);
outPut.innerText = '';
});
equals.addEventListener('click', () => {
secondValue = Number(outPut.innerText);
if (plusFirsValue && secondValue) {
outPut.innerText = add(plusFirsValue, secondValue);
console.log(add(plusFirsValue, secondValue));
} else if (subFirstValue && secondValue) {
outPut.innerText = subtract(subFirstValue, secondValue);
console.log(subtract(subFirstValue, secondValue));
} else if (multFirstValue && secondValue) {
outPut.innerText = multiply(multFirstValue, secondValue);
console.log(multiply(multFirstValue, secondValue));
} else if (divFirstValue && secondValue) {
outPut.innerText = divide(divFirstValue, secondValue);
console.log(divide(divFirstValue, secondValue));
}
});
allClear.addEventListener('click', () => {
outPut.innerText = '';
})
<div id="calculator-grid">
<div id="output"></div>
<button class="ac">AC</button>
<button class="sun">Sun</button>
<button class="divideOperator">÷</button>
<button class="number">7</button>
<button class="number">8</button>
<button class="number">9</button>
<button class="multiplyOperator">*</button>
<button class="number">4</button>
<button class="number">5</button>
<button class="number">6</button>
<button class="addOperator">+</button>
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button class="subtractOperator">-</button>
<button class="number">0</button>
<button class="number">.</button>
<button class="equals">=</button>
</div>
Some of the implementation I would like to do is a mix between operations that means, after a sum between 2 numbers I want to rest other. For example 3 + 3 = 6 but then 6 - 3 = 3 in the same operation. What can I do?
Notice that in your code the first selector (of button with class of 'number') you assign an array with less members than the second selector (where you select ALL the buttons) however in the loop you using the index of numbers.
const btn = document.getElementsByTagName('button');
const inp = document.getElementById('output');
for (let i = 0; i < btn.length; ++i) {
btn[i].addEventListener('click', () => {
inp.innerText += btn[i].innerText;
});
Event listeners added to all of the button and the innerText of the div with id of 'output' is modified by clicking one of the buttons.

Javascript - Help to update the display of my calculator to display the number of the button pressed

I'm building a calculator using HTML, CSS, and Javascript as a project. I have the HTML and CSS pretty much set - I'm having trouble coding the javascript so that I can interact with the HTML elements. I added event listeners to my number buttons - and on click I want them to update the text on the display. I can't quite figure out the correct method of doing this after researching for quite a while.
I've tried variations of updating the display through with eventListeners on my buttons and whichever number is pressed the display.textContent = button.innerText. But this doesn't update the integer on the display. Any help in the right direction would be helpful! thank you!
The HTML is below and the javascript is below that.
<body>
<div class = 'calculator-grid'>
<div class = 'output'>
<div class = 'previous-operand'></div>
<div data-display class = 'display'></div>
</div>
<button data-all-clear class = 'span-two grey-button'>AC</button>
<button data-delete class = 'grey-button'>DEL</button>
<button data-operator class = 'orange-button'>÷</button>
<button data-number >7</button>
<button data-number>8</button>
<button data-number>9</button>
<button data-operator class = 'orange-button'>*</button>
<button data-number>4</button>
<button data-number>5</button>
<button data-number>6</button>
<button data-operator class = 'orange-button'>+</button>
<button data-number>1</button>
<button data-number>2</button>
<button data-number>3</button>
<button data-operator class = 'orange-button'>-</button>
<button data-number class = 'span-two'>0</button>
<button data-number>.</button>
<button data-equals class = 'orange-button'>=</button>
</div>
const operatorButtons = document.querySelectorAll('[data-operator]');
const clearButton = document.querySelector('[data-all-clear]');
const deleteButton = document.querySelector('[data-delete]');
const equalButton = document.querySelector('[data-equals]');
const display = document.querySelector('[data-display]');
function updateDisplay() {
}
function clear() {
display.textContent = '';
}
clearButton.addEventListener('click', () => {
clear();
})
numberButtons.forEach(button => button.addEventListener('click',() => {
let buttonContent = button.innerText;
display.textContent = buttonContent;
}))
And here are my computing function which I'm going to call against the numbers I press.
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a , b) {
return a * b;
}
function divide(a, b) {
return a / b;
}
function operate(firstNum, secondNum, operator) {
let result = 0;
let operationResult;
switch (operator) {
case '+':
operationResult = add(firstNum, secondNum);
result += operationResult;
break;
case '-':
operationResult = subtract(firstNum, secondNum);
result += operationResult;
break;
case '*':
operationResult = multiply(firstNum, secondNum);
result += operationResult;
break;
case '÷':
operationResult = divide(firstNum, secondNum);
result += operationResult;
break;
}
return result;
}
Probably you forgot to define numberButtons?
Your code shows numberButtons has not been defined, after querySelectorAll number buttons and define them as numberButton, your code should work. See my code snippet.
const operatorButtons = document.querySelectorAll('[data-operator]');
const clearButton = document.querySelector('[data-all-clear]');
const deleteButton = document.querySelector('[data-delete]');
const equalButton = document.querySelector('[data-equals]');
const display = document.querySelector('[data-display]');
const numberButtons = document.querySelectorAll('[data-number]')
function updateDisplay() {
}
function clear() {
display.textContent = '';
}
clearButton.addEventListener('click', () => {
clear();
})
numberButtons.forEach(button => button.addEventListener('click',() => {
let buttonContent = button.innerText;
display.textContent = buttonContent;
}))
<div class = 'calculator-grid'>
<div class = 'output'>
<div class = 'previous-operand'></div>
<div data-display class = 'display'></div>
</div>
<button data-all-clear class = 'span-two grey-button'>AC</button>
<button data-delete class = 'grey-button'>DEL</button>
<button data-operator class = 'orange-button'>÷</button>
<button data-number >7</button>
<button data-number>8</button>
<button data-number>9</button>
<button data-operator class = 'orange-button'>*</button>
<button data-number>4</button>
<button data-number>5</button>
<button data-number>6</button>
<button data-operator class = 'orange-button'>+</button>
<button data-number>1</button>
<button data-number>2</button>
<button data-number>3</button>
<button data-operator class = 'orange-button'>-</button>
<button data-number class = 'span-two'>0</button>
<button data-number>.</button>
<button data-equals class = 'orange-button'>=</button>
</div>

Categories