javascriptdomevent-handlingevent-listener

"Clear" Button Function not Triggering in Simple Calculator App


I'm building a simple calculator app using HTML, CSS, and JavaScript. I’ve encountered an issue where the "Clear" button in my calculator does not seem to trigger the associated function.

Issue:

The displayAppend function works correctly when the calculator buttons are clicked, but the clear function is not getting triggered when the "C" button is clicked. I have confirmed that the console.log statement inside the clear function is not appearing in the console.

Here are the files I’m working with:

let disp = document.querySelector("#display");

function displayAppend(a) {
  disp.value += a;
}

function clear() {
  console.log("hi");
  disp.value = "";
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Calculator</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div id="calculator">
    <input id="display" readonly>
    <div id="key-container">
      <button onclick="displayAppend('+')" class="keys orange">+</button>
      <button onclick="displayAppend('7')" class="keys">7</button>
      <button onclick="displayAppend('8')" class="keys">8</button>
      <button onclick="displayAppend('9')" class="keys">9</button>
      <button onclick="displayAppend('-')" class="keys orange">-</button>
      <button onclick="displayAppend('4')" class="keys">4</button>
      <button onclick="displayAppend('5')" class="keys">5</button>
      <button onclick="displayAppend('6')" class="keys">6</button>
      <button onclick="displayAppend('*')" class="keys orange">*</button>
      <button onclick="displayAppend('1')" class="keys">1</button>
      <button onclick="displayAppend('2')" class="keys">2</button>
      <button onclick="displayAppend('3')" class="keys">3</button>
      <button onclick="displayAppend('/')" class="keys orange">/</button>
      <button onclick="displayAppend('0')" class="keys">0</button>
      <button onclick="displayAppend('.')" class="keys">.</button>
      <button onclick="Calculate()" class="keys">=</button>
      <button onclick="clear()" class="keys orange">C</button>
    </div>
  </div>
  <script src="calc.js"></script>
</body>

</html>

I have:

Then, why is the clear function isn't being called or if there's something I might have missed?


Solution

  • Rename the clear() function to clearDisplay() or something else. I'm not 100% sure why this happens, but I think it's because the clear() function already exists in a browser environment, and it is getting confused.