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 (0)