CodeNewbie Community 🌱

Jonathan Peters
Jonathan Peters

Posted on

A Simple Calculator Using HTML, CSS & JavaScript

Let's build a simple calculator using HTML, CSS, and JavaScript.
We'll start by creating the HTML structure for our calculator. This includes buttons for digits, operators, and other functionalities.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Calculator</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="calculator">
    <div id="display" class="display">0</div>
    <div class="buttons">
      <button id="clear">AC</button>
      <button id="divide">/</button>
      <button id="multiply">*</button>
      <button id="subtract">-</button>
      <button id="seven">7</button>
      <button id="eight">8</button>
      <button id="nine">9</button>
      <button id="add">+</button>
      <button id="four">4</button>
      <button id="five">5</button>
      <button id="six">6</button>
      <button id="one">1</button>
      <button id="two">2</button>
      <button id="three">3</button>
      <button id="equals">=</button>
      <button id="zero">0</button>
      <button id="decimal">.</button>
    </div>
  </div>
  <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 2: CSS Styling
We'll style the calculator to make it look clean and functional.

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background-color: #f0f0f0;
}

.calculator {
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 20px;
  background: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.display {
  background: #222;
  color: #fff;
  font-size: 2em;
  padding: 10px;
  margin-bottom: 10px;
  text-align: right;
  border-radius: 5px;
}

.buttons {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

button {
  padding: 20px;
  font-size: 1.5em;
  border: none;
  border-radius: 5px;
  background: #ddd;
  cursor: pointer;
  transition: background 0.3s;
}

button:hover {
  background: #ccc;
}
Enter fullscreen mode Exit fullscreen mode

Step 3: JavaScript Logic
We'll now implement the JavaScript logic to handle all the functionalities of the calculator.

document.addEventListener('DOMContentLoaded', () => {
  const display = document.getElementById('display');
  let currentInput = '';
  let operator = '';
  let previousInput = '';

  const updateDisplay = (value) => {
    display.textContent = value;
  };

  const handleNumberClick = (number) => {
    if (currentInput === '0' || operator === '=') {
      currentInput = number;
    } else {
      currentInput += number;
    }
    updateDisplay(currentInput);
  };

  const handleOperatorClick = (op) => {
    if (operator && currentInput && previousInput) {
      calculate();
    }
    operator = op;
    previousInput = currentInput;
    currentInput = '';
  };

  const handleEqualsClick = () => {
    calculate();
    operator = '=';
  };

  const handleClearClick = () => {
    currentInput = '0';
    operator = '';
    previousInput = '';
    updateDisplay(currentInput);
  };

  const handleDecimalClick = () => {
    if (!currentInput.includes('.')) {
      currentInput += '.';
    }
    updateDisplay(currentInput);
  };

  const calculate = () => {
    let result;
    const prev = parseFloat(previousInput);
    const curr = parseFloat(currentInput);

    switch (operator) {
      case '+':
        result = prev + curr;
        break;
      case '-':
        result = prev - curr;
        break;
      case '*':
        result = prev * curr;
        break;
      case '/':
        result = prev / curr;
        break;
      default:
        return;
    }
    currentInput = result.toString();
    updateDisplay(currentInput);
  };

  document.querySelectorAll('.buttons button').forEach(button => {
    button.addEventListener('click', () => {
      const { id } = button;
      if (id >= 'zero' && id <= 'nine') {
        handleNumberClick(button.textContent);
      } else if (id === 'add' || id === 'subtract' || id === 'multiply' || id === 'divide') {
        handleOperatorClick(button.textContent);
      } else if (id === 'equals') {
        handleEqualsClick();
      } else if (id === 'clear') {
        handleClearClick();
      } else if (id === 'decimal') {
        handleDecimalClick();
      }
    });
  });
});
Enter fullscreen mode Exit fullscreen mode

Explanation:
HTML: We created a simple structure with buttons for digits, operators, and other functionalities.
CSS: We styled the calculator to look clean and functional using flexbox and grid layouts.
JavaScript:
Event Listeners: We add event listeners to all buttons to handle clicks.
State Management: We manage states for

currentInput, operator,

and

previousInput.
Enter fullscreen mode Exit fullscreen mode

Functions:

updateDisplay:
Enter fullscreen mode Exit fullscreen mode

Updates the calculator's display.

handleNumberClick:
Enter fullscreen mode Exit fullscreen mode

Handles number button clicks.

handleOperatorClick:
Enter fullscreen mode Exit fullscreen mode

Handles operator button clicks.

handleEqualsClick:
Enter fullscreen mode Exit fullscreen mode

Handles the equals button click.

handleClearClick:
Enter fullscreen mode Exit fullscreen mode

Resets the calculator.

handleDecimalClick:
Enter fullscreen mode Exit fullscreen mode

Appends a decimal point to the current input.

calculate: 
Enter fullscreen mode Exit fullscreen mode

Performs the calculation based on the current operator.

Tips & Tricks:
Modularize Code: Break down your code into smaller functions to make it more readable and maintainable.
Use CSS Grid: CSS Grid is very powerful for creating layouts like this calculator.
Event Delegation: Use event delegation if you have many similar event listeners to optimize performance.

Top comments (3)

Collapse
 
lucy profile image
LucyMariee

Creating a simple calculator with HTML, CSS, and JavaScript teaches the basics of input, output, and logicβ€”just like the Starbucks menu calorie calculator processes your drink choices to show real-time nutritional info. Both are great examples of interactive, user-friendly tools!

Collapse
 
ariba12345 profile image
ariba12345

Looking to build a basic calculator for learning or your portfolio? In this guide, you’ll learn how to create a fully functional calculator using HTML, CSS, and JavaScript β€” no frameworks needed. Perfect for beginners and web development learners.

  1. HTML – Structure of the Calculator
    html
    Copy
    Edit
    <!DOCTYPE html>

    Simple Calculator AC / * - 7 8 9 + 4 5 6 = 1 2 3 0 . 🎨 2. CSS – Styling the Calculator css Copy Edit body { display: flex; justify-content: center; align-items: center; height: 100vh; background: #f4f4f4; font-family: Arial, sans-serif; }

.calculator {
background: #fff;
padding: 20px;
border-radius: 15px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
width: 260px;
}

display {

width: 100%;
height: 50px;
font-size: 1.5em;
margin-bottom: 10px;
text-align: right;
padding: 10px;
border: none;
background: #f1f1f1;
border-radius: 8px;
}

.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}

button {
padding: 15px;
font-size: 1.2em;
border: none;
background: #007bff;
color: white;
border-radius: 8px;
cursor: pointer;
transition: background 0.3s;
}

button:hover {
background: #0056b3;
}
βš™οΈ 3. JavaScript – Calculator Logic
javascript
Copy
Edit
let display = document.getElementById('display');

function appendValue(value) {
display.value += value;
}

function clearDisplay() {
display.value = '';
}

function calculate() {
try {
display.value = eval(display.value);
} catch (e) {
display.value = 'Error';
}
}

Collapse
 
chaimjoseph profile image
Chaim Joseph

Build a clean, functional calculator using HTML, CSS Grid, and JavaScript by structuring buttons, styling the layout, and handling input logic with modular functions.