Home / Project/ Calculator

Calculator

Building Calculator using HTML, CSS, JS

Table of Contents

What is Calculator?

It is a software program that required hardware to run, like the calculator app on your phone or computer. Think of a calculator as a smart math friend. It’s like a digital math assistant that can add, subtract, multiply, divide, and more. You type in numbers and it gives you the answers!

Step 1: Setting Up the HTML Structure

Create a new HTML file (e.g., index.html) and set up the basic structure:

HTML:

				
					 <div class="calculator">
    <div class="display">
      <input type="text" class="output" id="output" value="0" disabled >
    </div>
    <hr>
    <div class="buttons">
      <button class="clear" onclick="clearDisplay()">AC</button>
      <button onclick="appendNumber('7')">7</button>
      <button onclick="appendNumber('8')">8</button>
      <button onclick="appendNumber('9')">9</button>
      <button class="operator" onclick="setOperator('+')">+</button>
      <button onclick="appendNumber('4')">4</button>
      <button onclick="appendNumber('5')">5</button>
      <button onclick="appendNumber('6')">6</button>
      <button class="operator" onclick="setOperator('-')">-</button>
      <button onclick="appendNumber('1')">1</button>
      <button onclick="appendNumber('2')">2</button>
      <button onclick="appendNumber('3')">3</button>
      <button class="operator" onclick="setOperator('*')">*</button>
      <button class="operator" onclick="setOperator('/')">/</button>
      <button onclick="appendNumber('0')">0</button>
      <button class="operator" onclick="calculate()">=</button>
    </div>
  </div>
				
			
  • The calculator is enclosed in a ‘<div>’ with the class “calculator”.
  • It consists of a display area where numbers and results are shown.
  • Buttons for numbers (0-9) and operators (+, -, *, /) are organized in a button container.
  • Buttons have ‘onclick’ attributes that trigger functions for displaying numbers, setting operators, clearing the display, and performing calculations.

Step 2: Styling with CSS

Create a new CSS file (e.g., styles.css) to style your calculator:

CSS:

				
					 body {
    font-family: Arial, sans-serif;
  }
  .calculator {
    width: 350px;
    border: 2px solid #ccc;
    margin: 0px auto;
    padding: 10px;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  }
  .display {
    font-size: 20px;
    margin-bottom: 10px;
    text-align: right;
    padding: 5px;
      margin-right:8px;
      margin-left: -5px;
  }
  .output {
    width: 100%;
    height: 60px;
    font-size: 18px;
    padding-left: 5px;
  }
  .buttons {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-gap: 8px;
  }
  button {
    font-size: 20px;
    padding: 25px;
    cursor: pointer;
    border: none;
    border-radius: 5px;
  }
  button.operator {
    background-color: #5091fa;
    color: white;
  }
  button.clear {
    background-color: #e74c3c;
    color: white;
  }
  @media only screen and (max-width: 600px) {
  .calculator {
    width: 280px;
  }
    button {
    padding: 20px;
  }
}
				
			
  • Sets the default font for the entire page as Arial or a similar sans-serif font.
  • Styles the calculator container with a border, padding, rounded corners, and a subtle shadow for a 3D effect.
  • Styles the display area with font size, alignment, and padding.
  • Styles the display input element with width, height, font size, and padding.
  • Organizes the buttons using a CSS grid with 4 equal columns and a gap between them.
  • Styles buttons with font size, padding, cursor, and rounded corners.
  • Styles operator buttons with a blue background and white text.
  • Styles the “AC” button (clear button) with a red background and white text.
  • Implements responsive design for screens with a maximum width of 600px or less by adjusting the calculator width and button padding.

Step 3: Adding JavaScript Functionality

Create a new JavaScript file (e.g., script.js) to add functionality to your calculator:

JS:

				
					  let num1 = ""; 
  let operator = "";
  let num2 = ""; 
  let result = 0;
  let output = document.getElementById("output");
  function appendNumber(num) {
    if (operator === "") {
      num1 += num; 
    } else {
      num2 += num; 
    }
    updateDisplay();
  }
  function appendDecimal() {
    if (operator === "" && !num1.includes(".")) {
      num1 += ".";
    } else if (operator !== "" && !num2.includes(".")) {
      num2 += ".";
    }
    updateDisplay();
  }
  function updateDisplay() {
    output.value = num1 + " " + operator + " " + num2;
  }
  function clearDisplay() {
    num1 = "";
    operator = "";
    num2 = "";
    result = 0;
    updateDisplay();
  }
  function setOperator(op) {
    if (num1 !== "") {
      operator = op;
      updateDisplay();
    }
  }
  function calculate() {
    if (num1 !== "" && num2 !== "" && operator !== "") {
      let equation = num1 + " " + operator + " " + num2;
      switch (operator) {
        case "+":
          result = parseFloat(num1) + parseFloat(num2);
          break;
        case "-":
          result = parseFloat(num1) - parseFloat(num2);
          break;
        case "*":
          result = parseFloat(num1) * parseFloat(num2);
          break;
        case "/":
          result = parseFloat(num1) / parseFloat(num2);
          break;
      }
      num1 = result.toString();
      operator = "";
      num2 = "";
      updateDisplay(equation);
    }
  }
				
			
  • let num1 = "";, let operator = "";, let num2 = "";, let result = 0;: These variables store the first number, operator, second number, and result of calculations.

  • let output = document.getElementById("output");: This retrieves the element with the ID “output” from the HTML, which is the display area of the calculator.

  • function appendNumber(num): This function is used to add a number to either num1 or num2 depending on whether an operator has been set.

  • function appendDecimal(): This function adds a decimal point to either num1 or num2, ensuring only one decimal point exists.

  • function updateDisplay(): This function updates the display area with the current values of num1, operator, and num2.

  • function clearDisplay(): This function resets all variables to their initial state, effectively clearing the calculator display.

  • function setOperator(op): This function sets the operator (+, -, *, /) when a number has been entered.

  • function calculate(): This function performs the calculation based on the operator selected. It uses a switch statement to determine which operation to perform.

Step 4: Testing Your Calculator

Open your ‘index.html’ file in a web browser. Just right-click on html file and open with > select browser (like, Google Chrome). Now you can use a calculator on your Browser.

Conclusion

Congratulations! You’ve successfully created a calculator using HTML, CSS, and JavaScript.

FAQ's

This code helps you to create a calculator using HTML, CSS, and JavaScript that allows users to perform basic arithmetic operations like addition, subtraction, division, and multiplication.

Simply input numbers using the provided buttons, then select an operation (+, -, *, /), and finally, press the “=” button to see the result in the display.

No, you can’t. The code does not allow you to input decimal numbers.

Yes, the calculator is responsive.

Pressing the “AC” button clears the current input and resets the calculator, allowing you to start a new calculation.

After obtaining the result of a calculation, you can continue by entering new numbers and selecting another operation. The calculator retains the previous result as the first operand.

The code doesn’t handle division by zero. If you attempt to divide by zero, the calculator will display the result as “Infinity” or “NaN” (Not a Number).

No, you can’t chain operations together.

The calculator doesn’t have a built-in limit for the number of digits you can input, but extremely long numbers may not display correctly in the output area.

Yes, you can customize the design by adjusting the CSS styles.

Available Soon

guest
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments