Build a Calculator App

Learn to create a functional calculator using HTML, CSS, and JavaScript!

What You'll Learn

  • ✅ Create calculator HTML structure
  • ✅ Build interactive button grid
  • ✅ Handle user input and display
  • ✅ Implement mathematical operations
  • ✅ Use JavaScript eval() safely
  • ✅ Build a complete working calculator

Building a Calculator - Understanding the Architecture

🧮 What Makes a Calculator Work?

Think about a real physical calculator:

  • You press buttons (numbers and operations)
  • Numbers appear on a screen
  • When you press "=", it calculates the answer
  • The result appears on the screen

We're going to build the EXACT same thing, but on a webpage!

🏗️ The Three Essential Components

Every calculator needs these three parts working together:

1. The Display (Output Screen)

  • Shows what the user has typed
  • Shows the calculation result
  • Like the LCD screen on a physical calculator
  • We'll use an HTML <input> element set to readonly

2. The Buttons (Input Interface)

  • Number buttons: 0-9 and decimal point
  • Operation buttons: +, -, *, / (add, subtract, multiply, divide)
  • Function buttons: C (clear), = (calculate result)
  • We'll use HTML <button> elements arranged in a grid

3. The Logic (Brain)

  • JavaScript functions that run when buttons are clicked
  • Stores the current calculation as a string
  • Evaluates the mathematical expression when "=" is pressed
  • Updates the display with results

💡 How Calculator Logic Works - Behind the Scenes

When you type "5 + 3 =" on a calculator, here's what happens:

  1. You press "5" → Display shows "5"
  2. You press "+" → Display shows "5+"
  3. You press "3" → Display shows "5+3"
  4. You press "=" → Calculator evaluates the expression and shows "8"

The key insight: We build the calculation as a TEXT STRING first, then evaluate it!

// What the display contains at each step:
Step 1: "5"
Step 2: "5+"
Step 3: "5+3"
Step 4: Evaluate "5+3" → Result is 8

🎨 CSS Grid Layout - Arranging Buttons

How do we arrange buttons in a grid pattern?

We'll use CSS Grid, which is like creating a spreadsheet layout:

Grid Template Columns:

display: grid;
grid-template-columns: repeat(4, 1fr);

What this means:

  • display: grid; = "Use grid layout"
  • repeat(4, 1fr) = "Create 4 equal-width columns"
  • 1fr = "1 fraction" (each column gets equal space)

Visual representation:

Column1  Column2  Column3  Column4
   [7]      [8]      [9]      [/]
   [4]      [5]      [6]      [*]
   [1]      [2]      [3]      [-]
   [0]      [.]      [=]      [+]

Items automatically flow into the grid left-to-right, top-to-bottom!

⚙️ Understanding JavaScript Event Handlers

How do we make buttons DO something when clicked?

We use the onclick attribute:

<button onclick="appendToDisplay('5')">5</button>

Breaking it down:

  • onclick = "When this button is clicked..."
  • appendToDisplay = Name of the JavaScript function to run
  • ('5') = Pass the value '5' to the function

When user clicks the button:

  1. Browser detects the click event
  2. Browser looks for the onclick attribute
  3. Browser runs appendToDisplay('5')
  4. Our function adds '5' to the display!

🔍 Understanding eval() - The Calculation Engine

How does JavaScript calculate "5+3*2"?

We use the eval() function:

const expression = "5+3*2";
const result = eval(expression);
console.log(result); // Shows: 11

What eval() does:

  • Takes a STRING of JavaScript code
  • Executes it as if you typed it directly
  • Returns the result
  • Follows proper math order of operations (PEMDAS)

Examples:

  • eval("2+2") = 4
  • eval("10-5") = 5
  • eval("3*4") = 12
  • eval("10/2") = 5
  • eval("5+3*2") = 11 (multiplication happens first!)

⚠️ Important note: In real-world apps, eval() can be dangerous with user input from untrusted sources. But in our calculator, WE control what gets evaluated (only numbers and operators), so it's safe!

🎯 Readonly Inputs - Why the Display Can't Be Typed Into

Why use readonly?

<input type="text" id="display" value="0" readonly>

The readonly attribute means:

  • Users can see the content
  • Users can select/copy the text
  • But users CAN'T type directly into it
  • Only our JavaScript code can change the value

Why is this important?

  • On a real calculator, you can't write on the screen - you have to use the buttons!
  • It prevents users from typing invalid characters
  • It ensures our code has complete control over the display

🛠️ The Core JavaScript Functions We'll Build

appendToDisplay(value)

  • Adds a number or operator to the display
  • Example: If display shows "5" and user clicks "3", it becomes "53"
  • Used by all number and operator buttons

clearDisplay()

  • Resets the display back to "0"
  • Like the "C" button on a physical calculator
  • Clears any errors

calculate()

  • Takes the current display value
  • Uses eval() to calculate the result
  • Shows the result on the display
  • Handles errors if the expression is invalid

🎓 Interactive Exercises - Build Your Calculator!

🚀 Your Learning Journey

We'll build this calculator in 6 progressive steps:

  1. Exercise 1: Create the display screen (where numbers appear)
  2. Exercise 2: Add number buttons in a grid layout
  3. Exercise 3: Add operation buttons (+, -, *, /)
  4. Exercise 4: Add Clear and Equals buttons that span multiple columns
  5. Exercise 5: Write JavaScript to make buttons functional
  6. Exercise 6: Put it all together in a polished, complete calculator!

💡 By the end, you'll have a real calculator that works just like your phone's calculator app!

Exercise 1: Create the Display Screen
Not Started

Goal: Create the calculator's display screen where numbers and results will show.

Use a <div> with an <input> element to create the display.

Hint: The display uses an <input type="text"> with readonly so users can't type directly into it. The calculator will update it programmatically!
Click "Run Code" to see your calculator display!
Exercise 2: Add Number Buttons
Locked 🔒

Goal: Create buttons for numbers 0-9.

Add a <div> container with number buttons in a grid layout.

Hint: Use CSS Grid with grid-template-columns: repeat(3, 1fr) to create a 3-column layout. The buttons will automatically wrap to create rows!
Complete Exercise 1 to unlock...
Exercise 3: Add Operation Buttons
Locked 🔒

Goal: Add buttons for mathematical operations (+, -, *, /).

Add operation buttons with different styling to distinguish them from numbers.

Hint: Change the grid to 4 columns to fit the operations. Use a class operator to style operation buttons differently (orange looks good!).
Complete Exercise 2 to unlock...
Exercise 4: Add Clear and Equals Buttons
Locked 🔒

Goal: Add the Clear (C) and Equals (=) buttons to complete the button layout.

The Clear button should span multiple columns and the equals button should stand out.

Hint: Use grid-column: span 3 to make the Clear button take 3 columns, and grid-column: span 2 for the equals button. Different colors help: red for clear, green for equals!
Complete Exercise 3 to unlock...
Exercise 5: Add Calculator Logic
Locked 🔒

Goal: Make the calculator functional with JavaScript!

Add onclick attributes to buttons and create functions to handle clicks.

Hint: Key functions:
  • appendToDisplay() - Adds number/operator to display
  • clearDisplay() - Resets display to '0'
  • calculate() - Uses eval() to compute result
  • Check if display is '0' before appending
Complete Exercise 4 to unlock...
Exercise 6: Complete Working Calculator!
Locked 🔒

Final Challenge: Put it all together - a complete, working calculator with all features!

The calculator should handle all operations, clear, and display results correctly.

Hint: This calculator includes:
  • ✅ Beautiful gradient styling
  • ✅ Error handling with try/catch
  • ✅ Auto-reset after errors (1.5 seconds)
  • ✅ Hover effects on buttons
  • ✅ Professional color scheme
  • Test it: Try "5+3*2" to see order of operations work!
Complete Exercise 5 to unlock...