Build a Simple Calculator with JavaScript: Step-by-Step
This tutorial walks you through building a simple, functional calculator using HTML, CSS, and JavaScript. You’ll create a basic UI, wire up number and operator buttons, handle input and operator precedence simply, and add keyboard support.
What you’ll build
A calculator that supports:
- Basic operations: addition, subtraction, multiplication, division
- Decimal input and clearing (C / AC)
- Keyboard input for numbers, operators, Enter (=), Backspace, and Esc (clear)
Files
- index.html
- styles.css
- script.js
1. HTML structure
Create the calculator layout: a display and buttons.
index.html
html
<!doctype html> <html lang=“en”> <head> <meta charset=“utf-8” /> <meta name=“viewport” content=“width=device-width,initial-scale=1” /> <title>Simple JS Calculator</title> <link rel=“stylesheet” href=“styles.css” /> </head> <body> <div class=“calculator”> <div id=“display” class=“display”>0</div> <div class=“buttons”> <button class=“btn btn-ac” data-action=“clear”>AC</button> <button class=“btn btn-back” data-action=“back”>⌫</button> <button class=“btn btn-op” data-action=“operator”>%</button> <button class=“btn btn-op” data-action=“operator”>÷</button> <button class=“btn”>7</button> <button class=“btn”>8</button> <button class=“btn”>9</button> <button class=“btn btn-op” data-action=“operator”>×</button> <button class=“btn”>4</button> <button class=“btn”>5</button> <button class=“btn”>6</button> <button class=“btn btn-op” data-action=“operator”>−</button> <button class=“btn”>1</button> <button class=“btn”>2</button> <button class=“btn”>3</button> <button class=“btn btn-op” data-action=“operator”>+</button> <button class=“btn btn-zero”>0</button> <button class=“btn”>.</button> <button class=“btn btn-eq” data-action=“equals”>=</button> </div> </div> <script src=“script.js”></script> </body> </html>
2. CSS (basic styling)
styles.css “`css
- { box-sizing: border-box; } body { display: flex; height: 100vh; justify-content: center; align-items: center; background: #f5f7fb; font-family: system-ui, -apple-system, “Segoe UI”, Roboto, “Helvetica Neue”, Arial; } .calculator { width: 320px; background: #222831; border-radius: 12px; padding: 16px; box-shadow: 0 8px 24px rgba(0,0,0,0.2); } .display { background: #393e46; color: #e6eef4; font-size: 2rem; text-align: right; padding: 12px; border-radius: 8px; margin-bottom: 12px; min-height: 56px; overflow: hidden; word-break: break-all; } .buttons { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; } .btn { padding: 14px; font-size: 1.1rem; border: none; border-radius: 8
Leave a Reply