> Tiny Math

Assemble a Basic Calculator with HTML, CSS, and JavaScript.
Written by Mark VincentUpdated: September 2024

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:

  1. Set up the structure of the calculator using the DOM.
  2. Handle input from both the calculator buttons and the keyboard.
  3. Perform basic arithmetic operations and display the results on a virtual screen (LCD).

Let’s get started!

Table of Contents

Overview

Our calculator will include:

  • A virtual LCD display to show the current input and result.
  • Buttons for numbers, decimal, operators (addition, subtraction, multiplication, and division), and a reset button (C).
  • The ability to calculate the result when ENTER is pressed.
  • Keyboard support for convenience (e.g., +, -, *, /, ENTER, C).

Setup

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.

HTML Structure

<div id="display"></div> <div id="options"></div>

CSS (Basic Styling)

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.

Handling User Input

We need to handle input from the calculator buttons. The calculator will allow users to input numbers, perform operations, and reset when needed.

JavaScript Setup

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.

Creating the Display and Buttons

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); };

Performing Calculations

Our calculator needs to handle basic arithmetic operations. We’ll use a calculate function to execute the selected operation based on the current state.

The calculate Function

const 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.

Handling Operator Input

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; } };

Adding Keyboard Support

To enhance the user experience, we’ll add keyboard support. This allows users to interact with the calculator by pressing keys like +, -, *, /, and ENTER.

Listening for Keydown Events

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.

Conclusion

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!