Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 56 ยท Projects

Project: Calculator

Build a working calculator with jQuery: lay out the keypad, handle digits, decimals and operators with one delegated handler, and avoid floating-point surprises.

A calculator looks trivial, and that is why it is a good project: the buttons are easy, but the logic behind them (what happens when you press = twice, or two operators in a row, or 0.1 + 0.2) forces you to design the state properly. By the end you will have a keypad that works with mouse and keyboard and handles the awkward cases.

You will build it in three stages: the face, the state machine, and the polish.

Prerequisites

You should be comfortable with delegated events, data attributes and reading and setting text. No other library is needed.

Step 1: the face

Every key is a <button> with a data-key attribute naming what it does. Using real buttons gives you keyboard focus and screen-reader support for free. A single container holds them all, which lets one handler serve the whole keypad.

HTML
<div id="calc">
  <output id="screen">0</output>
  <div id="keys">
    <button data-key="clear">C</button>
    <button data-key="sign">+/-</button>
    <button data-key="percent">%</button>
    <button data-key="/">รท</button>
    <!-- digits, operators, dot and equals follow the same pattern -->
  </div>
</div>

A CSS grid with four columns turns the buttons into a keypad. Wide keys (zero) use grid-column: span 2.

Step 2: the state

A calculator is a tiny state machine. Instead of reading the screen to find out what to do, keep four values in variables:

Variable Meaning
entry the digits being typed now, as a string ("12.")
stored the left operand, as a number, or null
operator the pending operator ("+", "-", "*", "/") or null
fresh true right after an operator or =, so the next digit starts a new number

Keeping entry as a string matters. parseFloat("1.") is 1, which would swallow the decimal point the user just typed. Convert to a number only when you calculate.

The rules, in plain words:

  1. A digit appends to entry, unless fresh is true, in which case it replaces entry.
  2. A dot appends only if entry has none yet.
  3. An operator first finishes any pending operation (so 2 + 3 + shows 5), then stores the result and the new operator.
  4. Two operators in a row replace the operator instead of calculating.
  5. = finishes the pending operation and clears the operator.
  6. Division by zero shows an error message and resets.
Calculator, step by step

Two details deserve attention. First, .data("key") turns the text "7" into the number 7 (see type conversion), so the handler converts it back with String() before testing it. Reading with .attr("data-key") would avoid that. Second, tidy() uses toPrecision(12) and parseFloat to remove binary noise: without it 0.1 + 0.2 would show 0.30000000000000004.

Step 3: keyboard support and polish

A calculator that ignores the keyboard feels broken. Instead of duplicating the logic, translate key presses into clicks on the matching button. The click handler stays the single source of truth.

JavaScript
$(document).on("keydown", function (e) {
  var map = { Enter: "=", "=": "=", Escape: "clear", Backspace: "back", "*": "*", "/": "/", "+": "+", "-": "-", ".": "." };
  var key = /^[0-9]$/.test(e.key) ? e.key : map[e.key];
  if (!key) { return; }
  e.preventDefault();                       // stops "/" opening quick-find in some browsers
  $('#keys button[data-key="' + key + '"]').trigger("click");
});

A few more improvements worth making on your own:

  • Backspace. Remove the last character of entry; if nothing is left, set it back to "0".
  • History. Append each finished calculation to a list with .prepend(), and let a click on an entry reload its result.
  • Overflow. Limit entry to about 12 digits so it fits the screen, and show very large results in exponent form with toExponential().
  • Live region. The <output> is already a live region, so a screen reader announces results. Do not also move focus.

Never use eval() to evaluate the typed expression. It looks like the shortest calculator, but it runs any text as code, which is a security hole as soon as the input can come from a URL or a stored value. A small state machine like the one above is safer and gives you control over errors.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the current entry stored as a string and not a number?

    parseFloat("12.") is 12, so the point the user just typed would disappear. The string is converted to a number only when calculating.
  2. 2. What does the fresh flag do?

    After an operator or equals, the previous entry must not be extended. fresh tells the digit branch to replace it instead.
  3. 3. Why does the handler use .on("click", "button", ...) on #keys?

    Delegation attaches one handler to the container and uses the event bubbling from each button, which keeps the code short and the logic in one place.
  4. 4. Why is eval() a bad way to compute the displayed expression?

    eval executes arbitrary code. Even if your keypad only sends digits today, a future feature that feeds it other text turns into an injection hole.

Summary

  • Keep calculator state in four variables (entry, stored, operator, fresh) instead of reading the screen.
  • Hold the typed number as a string so decimals survive, and convert only when calculating.
  • One delegated click handler with a data-key on every button keeps the logic in one place; keyboard presses just trigger clicks.
  • Round with toPrecision() before displaying to hide floating-point noise, and handle division by zero explicitly.
  • Do not use eval().

Next: Project: Tic-Tac-Toe.