Everything you need as a full stack developer

Creating a simple calculator with HTML, CSS, and JavaScript

- Posted in Frontend Developer by

TL;DR You've just built a simple calculator from scratch using HTML, CSS, and JavaScript, creating a UI, styling with CSS, and adding interactivity with JavaScript to perform basic arithmetic operations.

Building a Simple Calculator: A Hands-on Guide

In this article, we'll embark on an exciting journey to create a simple calculator from scratch using HTML, CSS, and JavaScript. By the end of this tutorial, you'll have a fully functional calculator that can perform basic arithmetic operations.

Step 1: Setting Up the HTML Structure

Let's start by creating an HTML file called index.html and adding the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Calculator</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="calculator">
        <input type="text" id="display" disabled>
        <button class="btn" id="clear">C</button>
        <button class="btn" id="delete">DEL</button>
        <button class="btn" id="divide">/</button>
        <button class="btn" id="multiply">*</button>
        <button class="btn" id="subtract">-</button>
        <button class="btn" id="add">+</button>
        <button class="btn" id="equal">=</button>
    </div>

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

This HTML code sets up a basic structure for our calculator, including input fields and buttons.

Step 2: Styling with CSS

Next, let's create a CSS file called style.css and add the following code:

.calculator {
    width: 250px;
    height: 300px;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 10px;
}

#display {
    width: 100%;
    height: 40px;
    font-size: 24px;
    text-align: right;
    padding-right: 20px;
    border: none;
}

.btn {
    width: 60px;
    height: 50px;
    margin: 5px;
    border: none;
    background-color: #ccc;
    cursor: pointer;
}

#clear, #delete, #equal {
    width: 120px;
}

This CSS code styles our calculator with a clean and modern design.

Step 3: Bringing it to Life with JavaScript

Now, let's create a JavaScript file called script.js and add the following code:

const display = document.getElementById('display');
let number1 = '';
let operation = '';

document.querySelectorAll('.btn').forEach((button) => {
    button.addEventListener('click', () => {
        if (button.id === 'clear') {
            clearDisplay();
        } else if (button.id === 'delete') {
            deleteNumber();
        } else if (button.id === 'equal') {
            calculateResult();
        } else {
            appendDigit(button.textContent);
        }
    });
});

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

function deleteNumber() {
    display.value = display.value.slice(0, -1);
}

function appendDigit(digit) {
    if (display.value === '') {
        number1 += digit;
        display.value = number1;
    } else {
        display.value += digit;
    }
}

function calculateResult() {
    const number2 = parseFloat(display.value);
    let result;

    switch (operation) {
        case '+':
            result = number1 + number2;
            break;
        case '-':
            result = number1 - number2;
            break;
        case '*':
            result = number1 * number2;
            break;
        case '/':
            result = number1 / number2;
            break;
    }

    display.value = result.toString();
}

document.querySelectorAll('.btn').forEach((button) => {
    if (['+', '-', '*', '/'].includes(button.textContent)) {
        button.addEventListener('click', () => {
            operation = button.textContent;
            console.log(operation);
        });
    }
});

This JavaScript code brings our calculator to life by handling user input, performing calculations, and updating the display.

Conclusion

Congratulations! You've just built a simple calculator from scratch using HTML, CSS, and JavaScript. This project has taken you through the basics of front-end development, including creating a UI, styling with CSS, and adding interactivity with JavaScript.

Feel free to experiment with this code and try adding more features, such as storing previous calculations or allowing users to input decimal numbers.

Key Use Case

A Real-World Use Case: A Simple Calculator for a Small Business

Suppose you own a small bakery and want to create a simple calculator that can help you calculate the cost of ingredients, labor, and overheads for your baked goods. This calculator would be used by your employees to quickly estimate costs and make informed decisions.

Here's a workflow for implementing this use case:

  1. Design the Calculator: Create an HTML structure similar to the one in the article, with buttons for basic arithmetic operations (+, -, *, /) and input fields for numbers.
  2. Add Custom Buttons: Add custom buttons for common bakery calculations, such as "Cost of Ingredients", "Labor Cost", and "Total Cost".
  3. Implement Calculations: Use JavaScript to perform calculations based on the user's inputs and store previous calculations in local storage.
  4. Integrate with Inventory Management System: Connect the calculator to your inventory management system to retrieve real-time prices for ingredients and update the calculator accordingly.
  5. Test and Refine: Test the calculator with various scenarios and refine it as needed to ensure accuracy and user-friendliness.

This use case demonstrates how a simple calculator can be tailored to meet specific business needs, making it an essential tool for small businesses like your bakery.

Finally

A Calculator's Purpose: Simplifying Complex Calculations

The ability to perform complex calculations quickly and accurately is a fundamental aspect of any business or personal endeavor. With the rise of digital technologies, it's now possible to create simple calculators that can streamline tasks and reduce errors. By leveraging HTML, CSS, and JavaScript, developers can build intuitive interfaces and algorithms that make complex math operations accessible to users with varying levels of expertise.

In this context, a calculator is more than just a tool for basic arithmetic; it's an enabler of productivity, efficiency, and decision-making. Whether used in a business setting or personal life, a well-designed calculator can make a significant impact on daily routines and workflows.

Recommended Books

  • "Code Complete" by Steve McConnell: A comprehensive book on coding best practices, including advice on writing clean code and avoiding common pitfalls.
  • "Clean Code: A Handbook of Agile Software Craftsmanship" by Robert C. Martin: A guide to writing maintainable, readable, and efficient code.
  • "JavaScript: The Definitive Guide" by David Flanagan: A thorough reference for JavaScript developers, covering syntax, semantics, and best practices.
  • "HTML and CSS: Design and Build Websites" by Jon Duckett: A beginner-friendly book on web development, focusing on HTML and CSS basics.
  • "Eloquent JavaScript" by Marijn Haverbeke: A comprehensive guide to JavaScript programming, covering syntax, functions, objects, and more.
Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more