HomeJavaScriptHow to Build a JavaScript Calculator Quickly

How to Build a JavaScript Calculator Quickly

A JavaScript calculator is a basic application created using HTML for structure, CSS for styling, and JavaScript for functionality. It allows users to perform simple arithmetic operations such as addition, subtraction, multiplication, and division directly within their browser.

By leveraging JavaScript, the calculator becomes interactive, enabling the following features:

  1. Input Handling: Users can input numbers and operators by clicking buttons, and JavaScript will process these inputs.
  2. Real-time Calculations: The logic behind the calculator (handled by JavaScript) performs operations like addition (+), subtraction (-), multiplication (*), and division (/) instantly when the user presses the “=” button.
  3. Dynamic Display: The result of each operation is shown on the screen, simulating a real calculator.

The key components of a JavaScript calculator are:

  • HTML: Defines the layout and structure of the calculator, such as buttons and display.
  • CSS: Ensures the calculator is visually appealing and responsive across devices.
  • JavaScript: Handles logic, such as clearing input, deleting the last character, performing calculations, and error handling.

Create index.html file and copy code and paste code our layout.

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

    <script src="script.js"></script>
</body>
</html>

Create style.css file and copy code and paste code our layout.

  /* General Styles */
body {
    font-family: 'Arial', sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #ffff;
}

.calculator {
    width: 300px;
    background-color: #333;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.display {
    width: 100%;
    height: 60px;
    background-color: #222;
    color: #fff;
    font-size: 2em;
    text-align: right;
    padding-right: 20px;
    margin-bottom: 10px;
    border: none;
    border-radius: 10px;
    box-sizing: border-box;
}

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

button {
    width: 100%;
    height: 60px;
    font-size: 1.5em;
    background-color: #444;
    color: white;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

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

.back-btn {
    background-color: red;
    color: white;
}

.zero-btn {
    grid-column: span 2;
}

button:active {
    background-color: #666;
}

Create script.js file and copy code and paste code our layout.

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

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

// Delete the last character
function deleteLast() {
    let display = document.getElementById('display');
    display.value = display.value.slice(0, -1);
}

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

Explanation:

  1. HTML:
    • The structure of the calculator includes an input field (display) for showing the calculations and buttons for the digits and operators.
    • Each button has an onclick event handler that calls a corresponding JavaScript function.
  2. CSS:
    • The background color of the page is #ffff.
    • The calculator has a dark theme (#333 for background and #222 for the display).
    • The back button is styled with red (background-color: red) for distinction.
    • Buttons have responsive hover and active states for better interactivity.
  3. JavaScript:
    • appendToDisplay(value): Adds the clicked button’s value to the display.
    • clearDisplay(): Clears the display field.
    • deleteLast(): Deletes the last character from the display.
    • calculateResult(): Evaluates the current input and shows the result. If there’s an error (like invalid input), it displays “Error”.

This calculator is responsive and simple to use, with clean styling and interactive button functions.

Related Post

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Must Read

CATEGORY

spot_img