Calculator

How to create a calculator using HTML, CSS and JavaScript

How to create a calculator using HTML, CSS and JavaScript

Here’s a basic example of an advanced calculator with HTML, CSS, and JavaScript. This one includes

functions for addition, subtraction, multiplication, division, and square root.

We have already knew how to create the breadcrumbs navigation menu.

HTML Code

This code can be written in the notepad and save as index.html

Defines the structure with buttons for digits, operators, and functions.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Calculator</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="calculator">
        <input type="text" id="display" disabled>
        <div class="buttons">
            <button onclick="clearDisplay()">C</button>
            <button onclick="appendToDisplay('7')">7</button>
            <button onclick="appendToDisplay('8')">8</button>
            <button onclick="appendToDisplay('9')">9</button>
            <button onclick="appendToDisplay('/')">/</button>
            <button onclick="appendToDisplay('4')">4</button>
            <button onclick="appendToDisplay('5')">5</button>
            <button onclick="appendToDisplay('6')">6</button>
            <button onclick="appendToDisplay('*')">*</button>
            <button onclick="appendToDisplay('1')">1</button>
            <button onclick="appendToDisplay('2')">2</button>
            <button onclick="appendToDisplay('3')">3</button>
            <button onclick="appendToDisplay('-')">-</button>
            <button onclick="appendToDisplay('0')">0</button>
            <button onclick="appendToDisplay('.')">.</button>
            <button onclick="appendToDisplay('+')">+</button>
            <button onclick="calculateResult()">=</button>
            <button onclick="calculateSqrt()">√</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS Code

This code can be written in notepad and save as style.css

Styles the calculator for a neat appearance.

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

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

#display {
    width: 100%;
    height: 40px;
    text-align: right;
    margin-bottom: 10px;
    font-size: 1.5em;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

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

button {
    font-size: 1.2em;
    padding: 20px;
    border: none;
    border-radius: 5px;
    background-color: #eee;
    cursor: pointer;
}

button:hover {
    background-color: #ddd;
}

Javascript code

This code can be written in notepad and save as script.js

Handles logic for appending values, clearing the display, calculating results, and computing square roots.

function appendToDisplay(value) {
    document.getElementById('display').value += value;
}

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

function calculateResult() {
    try {
        let result = eval(document.getElementById('display').value);
        document.getElementById('display').value = result;
    } catch {
        document.getElementById('display').value = 'Error';
    }
}

function calculateSqrt() {
    try {
        let value = parseFloat(document.getElementById('display').value);
        if (value < 0) throw 'Error';
        let result = Math.sqrt(value);
        document.getElementById('display').value = result;
    } catch {
        document.getElementById('display').value = 'Error';
    }
}

Calculator Interface

Display: Shows the current input or result.

Buttons:

  • Numbers (0-9): Allow you to input numbers.
  • Operators (+, -, *, /): Perform basic arithmetic operations.
  • Decimal (.): Allows for decimal input.
  • Clear (C): Clears the display.
  • Equal (=): Evaluates the expression and shows the result.
  • Square Root (√): Computes the square root of the current value.

How It Works

Input: Clicking number buttons, operators, or decimal will append their values to the display.

Clear: Clicking the “C” button will clear the display.

Calculation: Clicking “=” will evaluate the expression shown in the display. This is handled by the eval() function in JavaScript, which computes the result of the expression.

Square Root: Clicking “√” will calculate the square root of the current number in the display and update it.

Result Examples

Here’s how the calculator would handle different inputs:

  1. Basic Arithmetic:
    • Input: 5 + 3 → Click = → Display: 8
    • Input: 12 / 4 → Click = → Display: 3
    • Input: 7 * 6 → Click = → Display: 42
    • Input: 9 - 2 → Click = → Display: 7
  2. Decimal Operations:
    • Input: 5.5 + 2.2 → Click = → Display: 7.7
    • Input: 7.1 / 3 → Click = → Display: 2.3666666666666667
  3. Square Root:
    • Input: 16 → Click → Display: 4
    • Input: 25 → Click → Display: 5
  4. Error Handling:
    • Input: 5 / 0 → Click = → Display: Infinity (which is a JavaScript result for division by zero)
    • Input: √ -9 → Click → Display: Error (since the square root of a negative number is not defined in the real number system)

Points to Note

  • eval(): This function is used for evaluating expressions. However, it’s generally discouraged for security reasons in more complex applications. For a production-level calculator, you might want to use a safer parser.
  • Error Handling: Basic error handling is in place. It catches invalid operations like taking the square root of a negative number.

This simple calculator can be enhanced with additional features, such as more advanced mathematical functions, error handling improvements, and a more sophisticated expression parser.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top