Welcome to this tiny tutorial! We’ll be building a simple yet functional calculator using only HTML, CSS, and vanilla JavaScript. We’ll be manipulating the DOM to create the interface, handle input, and perform basic arithmetic operations. If you’re looking to brush up on your DOM manipulation skills or build a foundational JavaScript project, this is the perfect exercise!
In this tutorial, we'll go over how to:
Let’s get started!
Our calculator will include:
C
).ENTER
is pressed.+
, -
, *
, /
, ENTER
, C
).First, we’ll start by setting up the calculator layout in the DOM. We’ll create the display for the calculator’s output and the buttons for numbers and operators.
<div id="display"></div> <div id="options"></div>
You can style your calculator however you want. Here’s a simple example for the layout:
#math { border: 5px solid #000; display: flex; flex-direction: column; align-items: center; } #lcd { font-size: 2em; margin-bottom: 10px; overflow: scroll; } button { padding: 10px; margin: 5px; font-size: 1.2em; }
Now that we have a structure in place, let’s jump into the logic of our calculator.
We need to handle input from the calculator buttons. The calculator will allow users to input numbers, perform operations, and reset when needed.
Here’s our basic JavaScript structure:
const nums = [1,2,3,4,5,6,7,8,9,'•', 0, 'c', 'ENTER']; const opps = ['add', 'sub', 'mul', 'div']; const defaultState = { currentInput: '', total: 0, currentOpp: null, };
We’ll use nums
for the number buttons and opps
for the operation buttons (add, subtract, multiply, divide). The calculator’s initial state is set in defaultState
, which includes:
currentInput
: stores the current user input.total
: holds the running total of calculations.currentOpp
: tracks the selected arithmetic operation.Let’s dynamically generate the display and buttons using JavaScript:
const generateMath = () => { let state = { ...defaultState }; let decimal = false; const math = document.createElement('div'); math.id = 'math'; const lcd = document.createElement('span'); lcd.id = 'lcd'; lcd.innerHTML = state.total; math.append(lcd); const numbers = document.createElement('div'); numbers.className = 'math-segment'; // Create number buttons nums.forEach(num => { let button = document.createElement('button'); button.innerHTML = num; if (num === 'c') button.style.color = 'red'; button.onclick = () => handleNumInput(num); numbers.append(button); }); math.append(numbers); document.getElementById('display').append(math); };
Our calculator needs to handle basic arithmetic operations. We’ll use a calculate
function to execute the selected operation based on the current state.
calculate
Functionconst calculate = () => { let currentValue = parseFloat(state.currentInput); switch(state.currentOpp) { case 'add': state.total += currentValue; break; case 'sub': state.total -= currentValue; break; case 'mul': state.total *= currentValue; break; case 'div': state.total /= currentValue; break; default: break; } state.currentInput = ''; lcd.innerHTML = state.total; };
The calculate
function takes the current input and performs the operation stored in state.currentOpp
. After the calculation, the result is displayed on the LCD.
We’ll use a handleOppInput
function to capture which operator the user selected and set it in our calculator’s state:
const handleOppInput = oppInput => { if (!state.currentInput.length) { state.currentOpp = oppInput; } else { calculate(); state.currentOpp = oppInput; } };
To enhance the user experience, we’ll add keyboard support. This allows users to interact with the calculator by pressing keys like +
, -
, *
, /
, and ENTER
.
const keyDown = e => { switch (e.key) { case '+': handleOppInput('add'); break; case '-': handleOppInput('sub'); break; case '*': handleOppInput('mul'); break; case '/': handleOppInput('div'); break; case 'Enter': handleNumInput('ENTER'); break; case 'c': handleNumInput('c'); break; default: if (nums.includes(parseInt(e.key))) handleNumInput(e.key); } }; document.addEventListener('keydown', keyDown);
This event listener captures keyboard inputs and triggers the corresponding button functionality. For instance, pressing +
calls the handleOppInput('add')
function, and pressing ENTER
triggers the calculation.
And there you have it! A fully functioning calculator using just HTML, CSS, and vanilla JavaScript. You can now add styling and extra features as you see fit. The code structure allows for easy expansion, so feel free to extend the calculator’s functionality or experiment with different designs.
Happy Hacking!