Summary: In this tutorial, you will learn to build a working calculator using HTML, CSS and JavaScript.

To build a calculator in JavaScript you would also need to use HTML and CSS to create a simple interface for the calculator.

Here is an example of how you can build a basic calculator using HTML, CSS and JavaScript:

calculator.html:

First, you can create the structure and layout of the calculator using HTML. Here is an example of the HTML code for a basic calculator with a display for the input and output, and buttons for the digits and operations:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <link rel="stylesheet" href="calculator.css">
</head>
<body>
    <div id="calculator">
        <div id="display">0</div>
        <button class="number">7</button>
        <button class="number">8</button>
        <button class="number">9</button>
        <button class="operator">+</button>
        <button class="number">4</button>
        <button class="number">5</button>
        <button class="number">6</button>
        <button class="operator">-</button>
        <button class="number">1</button>
        <button class="number">2</button>
        <button class="number">3</button>
        <button class="operator">*</button>
        <button class="clear">C</button>
        <button class="number">0</button>
        <button class="decimal">.</button>
        <button class="equal">=</button>
        <button class="operator">/</button>
      </div>
      <script src="calculator.js"></script>
</body>
</html>

calculator.css:

Next, you can add some styles to the calculator using CSS. Here is an example of how you can style the calculator to make it look like a traditional calculator:

#calculator {
  width: 250px;
  height: 400px;
  margin: 0 auto;
  background-color: #555;
  border-radius: 10px;
  box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.2);
  font-family: sans-serif;
  color: #fff;
}

#display {
  width: 100%;
  height: 50px;
  background-color: #333;
  border: none;
  font-size: 2em;
  text-align: right;
  padding: 20px;
  box-sizing: border-box;
}

button {
  width: 25%;
  height: 60px;
  background-color: #444;
  border: none;
  font-size: 1.5em;
  color: #fff;
  float: left;
}

button.operator {
  background-color: #666;
}

button.clear {
  background-color: #933;
}

button.equal {
  background-color: #393;
}

calculator.js:

Finally, you can use JavaScript to handle the user input, perform the calculations, and update the display. Here is an example of how you can use JavaScript to implement the basic functions of a calculator:

const calculator = document.querySelector('#calculator');
const display = document.querySelector('#display');

let firstOperand = null;
let operator = null;
let waitingForSecondOperand = false;

calculator.addEventListener('click', event => {
  if (event.target.classList.contains('number')) {
    inputNumber(event.target.innerText);
  } else if (event.target.classList.contains('operator')) {
    inputOperator(event.target.innerText);
  } else if (event.target.classList.contains('clear')) {
    clear();
  } else if (event.target.classList.contains('decimal')) {
    inputDecimal();
  } else if (event.target.classList.contains('equal')) {
    calculate();
  }
});

function inputNumber(number) {
  const displayValue = display.innerText;
  if (waitingForSecondOperand) {
    display.innerText = number;
    waitingForSecondOperand = false;
  } else {
    display.innerText = displayValue === '0' ? number : displayValue + number;
  }
}

function inputOperator(op) {
  const displayValue = display.innerText;
  if (firstOperand === null) {
    firstOperand = parseFloat(displayValue);
  } else if (operator) {
    const result = performCalculation(firstOperand, operator, parseFloat(displayValue));
    display.innerText = result;
    firstOperand = result;
  }
  operator = op;
  waitingForSecondOperand = true;
}

function clear() {
  firstOperand = null;
  operator = null;
  waitingForSecondOperand = false;
  display.innerText = '0';
}

function inputDecimal() {
  const displayValue = display.innerText;
  if (!displayValue.includes('.')) {
    display.innerText = displayValue + '.';
  }
}

function performCalculation(firstOperand, operator, secondOperand) {
  if (operator === '+') {
    return firstOperand + secondOperand;
  } else if (operator === '-') {
    return firstOperand - secondOperand;
  } else if (operator === '*') {
    return firstOperand * secondOperand;
  } else if (operator === '/') {
    return firstOperand / secondOperand;
  }
}

function calculate() {
  if (firstOperand && operator && !waitingForSecondOperand) {
    const result = performCalculation(firstOperand, operator, parseFloat(display.innerText));
    display.innerText = result;
    firstOperand = null;
    operator = null;
  }
}

The code starts by selecting the #calculator element and the #display element from the HTML using the querySelector method. These elements will be used to handle the user input and display the results.

Then, the code declares some global variables:

  • firstOperand will store the first operand of the calculation.
  • operator will store the operator for the calculation.
  • waitingForSecondOperand is a flag that indicates whether we are waiting for the second operand of the calculation.

Next, the code sets up an event listener for clicks on the calculator buttons. When a button is clicked, the code checks the class of the button and calls the appropriate function to handle the input.

The inputNumber function updates the display with the clicked number. If we are waiting for the second operand, the function sets the display to the clicked number and resets the waitingForSecondOperand flag. Otherwise, the function appends the clicked number to the current display value.

The inputOperator function stores the operator and the first operand, and sets the waitingForSecondOperand flag to true. If the first operand and the operator are already set, the function performs the calculation using the performCalculation function and updates the display with the result.

The clear function resets the first operand, the operator, the waitingForSecondOperand flag, and the display to their default values.

The inputDecimal function adds a decimal point to the display if it doesn’t already contain one.

The performCalculation function performs the calculation based on the provided operator and operands, and returns the result.

The calculate function checks if the first operand, the operator, and the waitingForSecondOperand flag are all set, and if so, performs the calculation using the performCalculation function and updates the display with the result.

Here is the final preview of the calculator:

JavaScript Calculator

That’s it! This is a basic example of how you can build a calculator in JavaScript using HTML, CSS, and JavaScript. You can customize and extend this code to add more functionality or improve the user interface as needed.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply