skip to Main Content
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


  1. 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.

    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);
                    });
    
                    // Move this line here
                    document.getElementsByClassName('up')[0].innerHTML = "";
                });
            });
            
            // Move this line outside of the operatorButtons loop
            numberButtons.forEach(button => {
                button.addEventListener("click", addNumber);
            });
    
            resultButton.addEventListener('click', result);
        }
    }
    
    Login or Signup to reply.
  2. 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

    const display = document.getElementById("display");
    const array = [];
    const calculate = array => eval(array.join(" ")); // do the calculation here
    document.getElementById("calc").addEventListener("click", (e) => {
      const tgt = e.target.closest("button"); // handle possible child elements like FontAwesome icons
      let currentVal = display.value;
      if (tgt.matches(".operator")) {
        array.push(tgt.textContent);
        display.textContent = array.join(" ");
        // do something with operator and values if needed
        return; 
      }
      else if (tgt.matches(".number")) {
        const number = tgt.textContent;
        if (array.length === 0) array.push(number)
        else if (array.length === 1) array[0] += number;
        else if (array.length === 2) array.push(number)
        else if (array.length === 3) array[2] += number;
        
        display.textContent = array.join(" ");
        // do something with number
        return; 
      }
      else if (tgt.id==="equals") {
        display.textContent = calculate(array);
      }
      else if (tgt.id==="clear") {
        display.textContent = "";
        array = [];
      }
    })
    <div id="display" style="border:1px solid black; width:100px; text-align: right;">0</div>
    <div id="calc">
      <button type="button" class="number" id="one">1</button>
      <button type="button" class="number" id="two">2</button>
      <button type="button" class="number" id="three">3</button>
      <button type="button" class="number" id="four">4</button>
      <button type="button" class="number" id="five">5</button>
      <button type="button" class="number" id="six">6</button>
      <button type="button" class="number" id="seven">7</button>
      <button type="button" class="number" id="eight">8</button>
      <button type="button" class="number" id="nine">9</button>
      <button type="button" class="number" id="zero">0</button>
    
      <button type="button" class="operator" id="add">+</button>
      <button type="button" class="operator" id="subtract">-</button>
      <button type="button" class="operator" id="multiply">*</button>
      <button type="button" class="operator" id="divide">/</button>
      <button type="button" id="equals">=</button>
      <button type="button" id="clear">C</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search