function aClick(){
if(a === undefined){
numberButtons.forEach(button => {
button.addEventListener("click", addNumber)
});
operatorButtons.forEach(button => {
button.addEventListener('click', function(){
a= parseInt(document.getElementsByClassName('up')[0].innerHTML)
operator = button.id
numberButtons.forEach(element => {
element.removeEventListener('click',addNumber)
});
})
});
document.getElementsByClassName('up')[0].innerHTML = "" //Line in question
numberButtons.forEach(button => {
button.addEventListener("click", addNumber)
});
resultButton.addEventListener('click', result)
}
}
I’m trying to build a calculator display that will delete the content after an operator button has been pressed (+,-,*,/). However, currently, nothing changes after I press the button. Whatever number I presses earlier still remains. What is going on? FYI, I will be providing the code to addNumber() and result():
function addNumber(Event){
document.getElementsByClassName('up')[0].innerHTML += Event.target.id
}
function result(){
resultButton.addEventListener('click', function(){
b = parseInt(document.getElementsByClassName('up')[0].innerHTML)
document.getElementsByClassName('down')[0].innerHTML=operate(a,operator,b)
})
}
2
Answers
To make sure that the display area content is cleared after an operator button is clicked, you should place the line document.getElementsByClassName(‘up’)[0].innerHTML = "" inside the event listener for the operator buttons. It should be placed within the callback function that is executed when an operator button is clicked.
Your code is very inefficient. You should never add an event handler in a click since it is added each time you click and I see you have then chose to remove it again each time.
Here is a DRYer way using delegation
You can use a parser on the array instead of eval
Evaluating a string as a mathematical expression in JavaScript