calculator.html 1.08 KB
<html>
  <body>
    <!--
      A simple calculator that only supports addition.
      It has an input where you can enter a number to add,
      a button that can be clicked to add it,
      and text that displays the current sum.
    -->
    <input type='number' id='number' />
    <button id='add'>+</button>
    <div id='sum'></div>

    <!--The JavaScript code that makes the calculator work-->
    <script>
      // Get the elements declared above in order to interact with them
      const numberInput = document.getElementById('number')
      const sumDisplay = document.getElementById('sum')

      // Show the current value of the `sum` variable in `<div id='sum'>`
      function showSum() {
        sumDisplay.innerText = String(sum)
      }

      // The sum starts at 0
      let sum = 0
      showSum()

      // Every time `<button id='add'>` is clicked,
      // add the number in `<input id='number'>` to the sum
      document.getElementById('add').addEventListener('click', () => {
        sum += Number(numberInput.value)
        showSum()
      })
    </script>
  </body>
</html>