top of page

Learn through our Blogs, Get Expert Help, Mentorship & Freelance Support!

Welcome to Colabcodes, where innovation drives technology forward. Explore the latest trends, practical programming tutorials, and in-depth insights across software development, AI, ML, NLP and more. Connect with our experienced freelancers and mentors for personalised guidance and support tailored to your needs.

blog cover_edited.jpg
Writer's picturesamuel black

Crafting a Simple Yet Powerful Calculator using HTML, CSS, and JavaScript.

In this tutorial, we will create a simple, functional calculator using HTML, CSS, and JavaScript. This calculator will support basic operations like addition, subtraction, multiplication, and division.

Calculator using HTML, CSS, and JavaScript. -colabcodes

Building a Calculator using HTML, CSS, and JavaScript.

Building a calculator using HTML, CSS, and JavaScript is an excellent project for beginners to learn the fundamentals of web development. HTML provides the structure of the calculator, including the display screen and buttons for digits and operations. CSS adds styling to make the calculator visually appealing, ensuring a clean and user-friendly interface. JavaScript is the powerhouse behind the functionality, enabling the calculator to handle user inputs, perform arithmetic operations, and display results dynamically. This project helps solidify concepts like event handling, DOM manipulation, and logical operations, offering a practical and fun way to understand the interaction between these core web technologies.


Setting Up the Project

Create a new folder for your project and inside it, create three files:


  1. index.html (structure of the calculator)

  2. style.css (styling of the calculator)

  3. script.js (logic for the calculator)


Write the HTML Code

Create the basic structure of the calculator in index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Calculator</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="calculator">
        <input type="text" id="display" disabled />
        <div class="buttons">
            <button class="btn">7</button>
            <button class="btn">8</button>
            <button class="btn">9</button>
            <button class="btn operator">/</button>
            <button class="btn">4</button>
            <button class="btn">5</button>
            <button class="btn">6</button>
            <button class="btn operator">*</button>
            <button class="btn">1</button>
            <button class="btn">2</button>
            <button class="btn">3</button>
            <button class="btn operator">-</button>
            <button class="btn">0</button>
            <button class="btn">.</button>
            <button id="clear" class="btn">C</button>
            <button class="btn operator">+</button>
            <button id="equals" class="btn">=</button>
       </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

Creating a JavaScript-powered calculator has never been so visually intuitive and functional! This simple HTML structure forms the backbone of an elegant, interactive calculator that you can bring to life with just a few more lines of CSS and JavaScript. The <div class="calculator"> houses an input display, ensuring all calculations are clearly visible, while the neatly organized buttons provide intuitive user interaction. Operators like +, -, /, and * are conveniently grouped with the digits, and the "C" (clear) button ensures users can reset the calculator effortlessly. Connecting this layout to a custom script.js file allows for dynamic functionality, while style.css ensures a visually appealing design. It’s a clean, modular approach that’s perfect for both beginners and enthusiasts exploring the world of web development.


Style the Calculator with CSS

Add styling to make the calculator visually appealing in style.css:

body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f3f3f3;
    margin: 0;
}

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

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

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

.btn {
    background: #f0f0f0;
    border: none;
    border-radius: 5px;
    height: 50px;
    font-size: 1.2rem;
    cursor: pointer;
    transition: background 0.3s ease;
}

.btn:active {
    background: #ddd;
}

.operator {
    background: #ffa726;
    color: white;
}

.operator:active {
    background: #fb8c00;
}

#clear {
    background: #f44336;
    color: white;
}

#clear:active {
    background: #d32f2f;
}

#equals {
    background: #4caf50;
    color: white;
    grid-column: span 2;
}

#equals:active {
    background: #388e3c;
}

This CSS defines a clean and responsive layout for a calculator interface, emphasizing usability and aesthetics.

The body acts as the container for the entire page, utilizing Flexbox for centering both horizontally and vertically. The alignment properties ensure the calculator is positioned precisely in the center of the viewport, while a 100vh height allows it to occupy the full vertical space. A light gray background adds subtle contrast, and the removal of default margins ensures a seamless, edge-to-edge layout.

The calculator component itself is styled as a fixed-width container with a minimalistic design. It features a white background, rounded corners achieved through a border-radius property, and a soft box-shadow to create depth. Padding is used internally to maintain spacing between the content and edges, while the width is kept consistent to preserve proportionality.

The display area of the calculator is styled for functionality and clarity. It spans the full width of the container, with a height sufficient for readability. A larger font size ensures visibility, while right-aligned text mimics traditional calculator designs. The display is bordered with a subtle outline and slight padding for clear demarcation and enhanced user interaction.

The buttons are structured within a CSS grid layout, creating uniform spacing and sizing across all elements. The grid configuration ensures visual alignment and ease of navigation. Buttons feature rounded edges, neutral gray backgrounds, and smooth transition effects for hover and active states, enhancing the interactive experience. Key functional buttons, such as operators, clear, and equals, are distinguished with bold colors (e.g., orange, red, green) to improve visibility and usability.

Active states are applied to buttons for dynamic feedback. On interaction, color transitions simulate a tactile response, enhancing the user experience. This design approach combines technical precision with a focus on intuitive, visually appealing functionality.

Add JavaScript Logic to HTML & CSS

Implement the functionality in script.js:

// Get references to the display and buttons
const display = document.getElementById('display');
const buttons = document.querySelectorAll('.btn');
const clearButton = document.getElementById('clear');
const equalsButton = document.getElementById('equals');

// Variables to store values and operator
let currentOperand = '';
let previousOperand = '';
let operator = null;

// Function to update the display
function updateDisplay() {
    display.value = currentOperand;
}

// Function to handle number and decimal button clicks
buttons.forEach(button => {
    button.addEventListener('click', () => {
        const value = button.textContent;

        if (!isNaN(value) || value === '.') {
            currentOperand += value;
            updateDisplay();
        } else if (['+', '-', '*', '/'].includes(value)) {
            if (currentOperand === '') return;
            operator = value;
            previousOperand = currentOperand;
            currentOperand = '';
        }
    });
});

// Function to handle clear button
clearButton.addEventListener('click', () => {
    currentOperand = '';
    previousOperand = '';
    operator = null;
    updateDisplay();
});

// Function to handle equals button
equalsButton.addEventListener('click', () => {
    if (currentOperand === '' || operator === null) return;

    let result;
    const prev = parseFloat(previousOperand);
    const curr = parseFloat(currentOperand);
    
	switch (operator) {
        case '+':
            result = prev + curr;
            break;
        case '-':
            result = prev - curr;
            break;
        case '*':
            result = prev * curr;
            break;
        case '/':
            result = prev / curr;
            break;
        default:
            return;
    }

    currentOperand = result.toString();
    previousOperand = '';
    operator = null;
    updateDisplay();
});

This JavaScript code implements the logic for a basic calculator. It handles user inputs, performs arithmetic operations, and updates the display. Here's a detailed explanation:


References and Initial Setup

  • Display and Buttons: The display is linked to the input field where results are shown, while buttons references all elements with the class .btn. The clearButton and equalsButton are specifically assigned to their respective functions.

  • Variables:

currentOperand holds the current input from the user.

previousOperand stores the value entered before the current operation.

operator keeps track of the selected arithmetic operator.


Display Update

The updateDisplay function ensures that the display always reflects the value of currentOperand. Whenever a change is made to currentOperand, this function is called to synchronize the visual output.


Button Click Handling

Each button is given an event listener:

  • Number and Decimal Inputs: If the button's text content is a number or a decimal point, its value is appended to currentOperand. This allows users to build multi-digit numbers or include a decimal.

  • Operator Buttons: When an operator is clicked, the current number (currentOperand) is stored in previousOperand, and currentOperand is reset for the next input. The selected operator is stored for later calculations.


Clear Button

The clearButton resets all variables to their initial state (currentOperand, previousOperand, and operator) and updates the display to reflect the cleared state.


Equals Button

When the equalsButton is clicked:


  1. It checks if the necessary inputs (currentOperand and an operator) are present. If not, the function exits early.

  2. The stored operands (previousOperand and currentOperand) are parsed into numbers using parseFloat.

  3. A switch statement performs the calculation based on the selected operator. Supported operations include addition, subtraction, multiplication, and division.

  4. The result is converted to a string, assigned to currentOperand, and displayed. The previous inputs and operator are cleared.


Features

  • The calculator dynamically updates the display, ensuring real-time feedback.

  • Operators and the clear button ensure proper sequencing of operations.

  • It handles edge cases, such as missing inputs or operators, gracefully by using conditional checks.


This code provides the core functionality of a basic calculator with a clean and structured implementation.


Conclusion

This project elegantly combines HTML, CSS, and JavaScript to create a functional and visually appealing calculator. The design prioritizes clarity and usability, with a sleek interface styled through CSS. The layout is responsive, ensuring that all components are evenly spaced and intuitive to interact with.

On the functionality side, JavaScript powers the calculator's interactivity. The logic handles user inputs, manages operations, and dynamically updates the display, ensuring a seamless experience. Features like active states for buttons and error handling make the application both robust and user-friendly.

Overall, this calculator is a great example of how web technologies can work together to build something practical and elegant. Whether you're a beginner looking to practice coding or an enthusiast exploring web development, this project provides a strong foundation for mastering core concepts. Keep experimenting, and watch your ideas come to life!

Commentaires


Get in touch for customized mentorship and freelance solutions tailored to your needs.

bottom of page