Step 6 / 1155%

Step 6

Entering Digits and the Decimal Point

20 min

Add digits to the display and handle the decimal point with a single click listener.

Definition

An event listener is a function that the browser calls automatically when a specific event occurs on an element of the page: a click, a key press, a hover, and so on. You attach it with addEventListener, specifying the type of event to watch and the function to run. Without a listener, the page is displayed but reacts to nothing: the listener is what connects the user to your code.

The first real interaction: typing digits. So far, the calculator has a state and a display, but nothing connects them to the keys. That is what we are going to build now, and this is where the page finally comes alive.

We proceed in two steps: first, functions that modify the state, then a listener that calls them. This separation is deliberate. The functions know nothing about the HTML or the clicks: they only transform the state object. The listener, for its part, knows nothing about the calculator's rules: it simply relays what the user did. Each has its own role, and the code stays easy to read, test and fix.

1. Adding a digit

Before writing the function that adds a digit, we need to remember what the state contains: state.current is the number currently being typed, stored as a string , not as a number. This is an important choice: with a string, typing 0 then 5 gives "05", which we can correct, whereas with a number we would lose track of what the user actually typed, notably the zeros after the decimal separator.

calculator.js (before updateDisplay();)
function countDigits(value) {
  return value.replace("-", "").replace(".", "").length;
}

function appendDigit(digit) {
  if (state.overwrite) {
    state.current = digit;
    state.overwrite = false;
    state.expression = "";
  } else if (state.current === "0") {
    state.current = digit;
  } else if (countDigits(state.current) < MAX_DIGITS) {
    state.current += digit;
  }
}

The countDigits function counts only the real digits: it removes the minus sign and the decimal point before measuring the length. This way, -12.5 counts as three digits, not five characters. Without this, a negative or decimal number would be limited sooner than a positive integer, which would be surprising for the user.

There are three possible cases when a digit is typed:

  • overwrite is true : we start a new number, and the digit replaces the display. This happens, for example, right after pressing =: if the user types a digit, they want to start over from zero, not extend the previous result. We also clear the expression displayed above, which no longer has any reason to be there.
  • The display shows 0 : we replace it, to avoid getting 07. The initial zero is only a "placeholder", not a real digit entered by the user.
  • Otherwise : we append the digit at the end, as long as we have not exceeded MAX_DIGITS. Beyond the limit, the digit is simply ignored: no error, no message, the input just "stops".

Why a limit on digits? A calculator display has a fixed width. Without a cap, a number that is too long would overflow the display, and JavaScript loses precision beyond about fifteen to sixteen significant digits. It is better to block the input than to display a wrong result.

Here is how state.current evolves when we type 0, 7, 3 in succession:

  • At the start, state.current is "0". We type 0: the display is already "0", so it is replaced by "0". Nothing changes, and that is as it should be.
  • We type 7: the display is "0", so "7" replaces it (and not "07").
  • We type 3: the display is no longer "0", the limit has not been reached, so the digit is appended at the end: "73".

2. The decimal comma

The decimal comma requires more precautions than a digit, because it can appear only once in a number. It follows the same logic as appendDigit, with its own rules.

calculator.js (continued)
function appendDecimal() {
  if (state.overwrite) {
    state.current = "0.";
    state.overwrite = false;
    state.expression = "";
  } else if (!state.current.includes(".")) {
    state.current += ".";
  }
}
  • Internally we use the point (this is what JavaScript understands); the comma is only a display matter. The updateDisplay function is responsible for replacing the point with a comma when showing the number on screen. The state thus stays clean and computable, and the display follows French conventions.
  • includes(".") prevents writing 1.2.3: only one decimal separator per number. If the point is already there, the function does nothing: the second press of the comma is silently ignored.
  • If we start a new number by typing the comma, we get 0. rather than a bare point. This is how all calculators behave: typing , then 5 gives 0,5.
  • Unlike appendDigit, the comma does not check MAX_DIGITS: the point is not a digit, and countDigits ignores it anyway.

3. A single listener for all the keys

Instead of placing 20 listeners, we place just one on the container. A click on a key "bubbles up" to it: this is event delegation .

Why this approach? First, it is more economical: a single listener in memory rather than twenty. Second, it is easier to maintain: if we add a key to the HTML tomorrow, it will work without touching the JavaScript. Finally, it relies on a natural browser mechanism: when you click an element, the event "bubbles" (bubbling) up to its parents, which lets the container intercept it as it passes.

calculator.js (before updateDisplay();)
const actions = {
  decimal: appendDecimal,
};

keys.addEventListener("click", (event) => {
  const button = event.target.closest("button");
  if (!button) return;

  const { digit, action } = button.dataset;

  if (digit !== undefined) {
    appendDigit(digit);
  } else if (action && actions[action]) {
    actions[action]();
  }

  updateDisplay();
});
  • event.target.closest("button") finds the key that was clicked, even if the click lands on its text. Indeed, event.target designates the most specific element that received the click (sometimes an element inside the button); closest walks up the tree to the nearest button. If the click was beside the keys, it returns null.
  • The line if (!button) return; immediately exits the function in that case: a click in the gap between two keys must not trigger anything.
  • button.dataset reads the data-* attributes: for data-digit="7", digit is "7". It is undefined if the key does not have this attribute. Note: we test digit !== undefined and not if (digit), because the string "0" is an existing value that must absolutely not be confused with the absence of a value.
  • actions is a dictionary that maps an action name to a function: actions[action]() calls the right one. The actions[action] test ignores keys that are not programmed yet. Later, adding a feature will simply mean adding a line to this dictionary.
  • updateDisplay() ends every click: the screen always reflects the state. This rule avoids any omission: whatever the key, we modify the state and then redraw, in that order.

4. The complete path of a click

To tie everything together, let's follow what happens when the user clicks the 7 key:

  • The browser detects the click and creates an event object; the event bubbles up from the button to the keys container.
  • Our listener fires and finds the button thanks to closest.
  • It reads data-digit="7" and calls appendDigit("7").
  • appendDigit updates state.current according to one of the three cases.
  • updateDisplay() re-reads the state, formats the number the French way and writes it to the screen.

5. Common mistakes

  • Forgetting updateDisplay() : the state changes correctly behind the scenes, but the screen stays frozen. If nothing moves, check this call first.
  • Inserting the code after the initial updateDisplay(); : the block titles say "before updateDisplay();" for a reason: the functions and the listener must exist before the first display.
  • Storing the number as a real number : current += digit would then add instead of concatenate. That is why we keep strings during input and only convert at calculation time.
  • Writing data-digit and reading dataset.data-digit : the data- prefix disappears in dataset; you simply read dataset.digit.
French formatting: thousands separator space and decimal comma.

It reacts! Every key already does something.

Checkpoint

Type 1 2 3 4 , 5 6: the display shows 1 234,56. Try typing two commas (the second is ignored), then more than 12 digits (the input stops). Also try starting with the comma: you should get 0,, then 0,5 when you type 5. Finally, type several zeros in a row: the display should stay on 0. The operators and = do nothing for now: that is normal, they will be the subject of the next lesson.