DEV Community

Cover image for BUILDING A SIMPLE WEB-BASED CALCULATOR: Step-by-step Guild with Html CSS And JavaScript
JUDE EZE
JUDE EZE

Posted on

BUILDING A SIMPLE WEB-BASED CALCULATOR: Step-by-step Guild with Html CSS And JavaScript

Creating a calculator web application is a fantastic project for learning HTML, CSS, and JavaScript. Even though calculators are commonplace or rather ordinary , building one from scratch helps beginners understand fundamental concepts of web development—such as structuring content with HTML, styling elements with CSS, and adding interactive functionality with JavaScript.

In this overview, we’ll walk through every part of the code needed to create a fully functional calculator. This guide will not only provide the code but will also explain each line in detail, ensuring you understand how everything fits together. By the end of this project, you’ll have a smooth, interactive calculator that you can personalize or even expand upon with more advanced features.

The Calculator’s Features
This calculator includes basic functionality:

A display area to show the current input and results.

Number buttons (0–9) and an additional "00" button.

Arithmetic operation buttons: addition (+), subtraction (-), multiplication (*), and division (/).

Special buttons:

  • AC to clear the current input.

  • DEL to delete the last character.

  • +/- to toggle between positive and negative numbers.

  • = to evaluate the expression and show the result.

With this project, you’ll learn how to:

  • Create a user interface with HTML.

  • Style elements using CSS to improve the visual appeal.

  • Implement calculator logic using JavaScript to handle button
    interactions and perform calculations.

STEP 1: HTML STRUCTURE - BUILDING THE CALCULATOR'S LAYOUT

The HTML code provides the foundational structure for our calculator. In this part, we define the elements that will make up our calculator, such as buttons and a display area, you can use any editor of your choice for this effect, I personally prefer Visual studio code. Here’s the complete HTML code for the calculator:



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="calculator">
        <input type="text" placeholder="0" id="inputbox" disabled>
         <div>
         <button class="clearbtn">AC</button>
         <button class="actionbtn">DEL</button>
         <button id="plus_min" class="actionbtn">+/-</button>
         <button class="actionbtn">/</button>
        </div>

         <div>
            <button>7</button>
            <button>8</button>
            <button>9</button>
            <button class="actionbtn">*</button>
        </div>

         <div>
            <button>4</button>
            <button>5</button>
            <button>6</button>
            <button class="actionbtn">-</button>
        </div>

         <div>
            <button>1</button>
            <button>2</button>
            <button>3</button>
            <button class="actionbtn">+</button>
        </div>

        <div>
            <button>00</button>
            <button>0</button>
            <button>.</button>
            <button class="enter">=</button>
        </div>
    </div>

    <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Explanation

Document Type and Language Declaration:

<!DOCTYPE html>
Enter fullscreen mode Exit fullscreen mode

Tells the browser that this is an HTML5 document.

<html lang="en">
Enter fullscreen mode Exit fullscreen mode

Begins the HTML document and specifies English as the language. This helps search engines and screen readers understand the language of the document.

Head Section:

<head>
Enter fullscreen mode Exit fullscreen mode

Contains metadata and links significant to the document but not visible to the user.

<meta charset="UTF-8">
Enter fullscreen mode Exit fullscreen mode

Sets the character encoding, ensuring compatibility with most languages.

<meta name="viewport" content="width=device-width, initial-scale=1.0">
Enter fullscreen mode Exit fullscreen mode

Makes the page responsive by adjusting its layout to fit different devices.

<title>Calculator</title>
Enter fullscreen mode Exit fullscreen mode

Sets the title displayed on the browser tab.

<link rel="stylesheet" href="style.css">
Enter fullscreen mode Exit fullscreen mode

Links to the CSS file where styles are defined.

Calculator Layout:

<div class="calculator">
Enter fullscreen mode Exit fullscreen mode

Wraps the entire calculator interface. We’ll apply styles to this container to make it look like a calculator.

<input type="text" placeholder="0" id="inputbox" disabled>
Enter fullscreen mode Exit fullscreen mode

This is the display area of the calculator, where we show the current number or result. It is disabled, so users can’t type directly.

Buttons:

<button class="clearbtn">AC</button>
Enter fullscreen mode Exit fullscreen mode

Clears the calculator display and resets the current calculation.

<button class="actionbtn">DEL</button>
Enter fullscreen mode Exit fullscreen mode

Deletes the last entered character.

<button id="plus_min" class="actionbtn">+/-</button>
Enter fullscreen mode Exit fullscreen mode

Toggles between positive and negative values.

<button class="actionbtn">/</button>
Enter fullscreen mode Exit fullscreen mode

The division operator.

Remaining button elements represent numbers (0–9), operators (+, -, *, /), and a decimal point (.). The = button (class="enter") is used to evaluate the expression.

JavaScript File:

<script src="script.js"></script>
Enter fullscreen mode Exit fullscreen mode

Links to the JavaScript file that handles the calculator’s functionality.

STEP 2: CSS STYLING - DESIGNING THE CALCULATOR INTERFACE

Now that we have the structure, let’s move to the styling. This CSS code will make the calculator look more modern, adding colors, rounded buttons, shadows, and responsive layout adjustments.

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: 'poppins', sans-serif;
}
body{
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: linear-gradient(45deg, #0a0a0a, #3a4452);
}
.calculator{
    border: 1px solid #a2a2a2;
    padding: 20px;
    border-radius: 20px;
    background: transparent;
    box-shadow: 0px 3px 15px rgba(113, 115, 119, 0.5);
}
input{
    width: 272px;
    min-height: 100px;
    border: none;  
    padding: 5px;
    margin: 10px;
    background: transparent;
    font-size: 40px;
    text-align: right;
    cursor: text;
    outline: none;
    color: #fff;
}
input::placeholder{
    color: #fff;
}
.calculator button{
    width: 50px;
    height: 50px;
    margin: 10px;
    border-radius: 50%;
    border: none;
    box-shadow: -5px 3px 10px rgba(9, 9, 9, 0.5);
    background: transparent;
    color: #fff;
    cursor: pointer;
    outline: none;
}
.calculator .actionbtn{
    color: #1afe17;
}
.calculator .clearbtn{
    background: #f31d1f;
}
.calculator .enter{
    background: #f5881a;
}
Enter fullscreen mode Exit fullscreen mode

Explanation

Basic Reset and Font:

* { padding: 0; margin: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
Enter fullscreen mode Exit fullscreen mode

Removes default padding and margins, sets box-sizing to border-box for consistent sizing, and applies a modern font.

Body Styling:

body: Uses Flexbox to center the calculator container in the middle of the screen and applies a gradient background.

Calculator Container:

.calculator: Adds padding, rounded corners, and a shadow for a neat, card-like appearance.

Display Input:

input: This styling gives the display area a large font size and right alignment, resembling a real calculator display.

Button Styling:

.calculator button: Sets up a circular button with a shadow effect, white text color, and spacing for alignment.

.actionbtn, .clearbtn, and .enter: Styles for specific buttons to make them stand out (e.g., green for operators, red for clear, and orange for equal).

STEP 3: THIS IS WHERE ALL THE JAVASCRIPT LOGIC HAPPENS - MAKING THE CALCULATOR FUNCTIONAL

With structure and style well accomplished, lets add a functionality using JavaScript. This script allows us to handle click on buttons, perform arithmetic, and display results.

document.addEventListener('DOMContentLoaded', () => {
    let input = document.getElementById('inputbox');
    let buttons = document.querySelectorAll('button');
    let string = "";
    let arr = Array.from(buttons);

    arr.forEach(button => {
        button.addEventListener('click', (e) => {
            if (input.value.length > 10) {
                input.style.fontSize = '16px';
            } else {
                input.style.fontSize = '40px';
            }

            if (e.target.innerHTML === "=") {
                try {
                    string = eval(string).toString();
                    input.value = string;
                } catch (error) {
                    input.value = "Error";
                    string = "";
                }
            } else if (e.target.innerHTML === 'AC') {
                string = "";
                input.value = string;
            } else if (e.target.innerHTML === "DEL") {
                string = string.substring(0, string.length - 1);
                input.value = string;
            } else {
                string += e.target.innerHTML;
                input.value = string;
            }
        });
    });

    document.getElementById('plus_min').addEventListener('click', () => {
        if (string) {
            const number = parseFloat(string);
            string = (number * -1).toString();
            input.value = string;
        }
    });
});

Enter fullscreen mode Exit fullscreen mode

Explanation

Event Listener for Page Load:

document.addEventListener('DOMContentLoaded', () => { ... })
Enter fullscreen mode Exit fullscreen mode

Ensures the script runs after all HTML content is loaded.

Input and Button Variables:

let input = document.getElementById('inputbox')
Enter fullscreen mode Exit fullscreen mode

Selects the display area.

let buttons = document.querySelectorAll('button')
Enter fullscreen mode Exit fullscreen mode

Collects all buttons in an array for easy manipulation.

Button Click Events:

button.addEventListener('click', (e) => { ... })
Enter fullscreen mode Exit fullscreen mode

Adds a click event to each button. Depending on the button, different actions are performed:

Display Font Size Adjustment: Reduces font size when input length exceeds 10 characters.

Equal Sign (=): Evaluates the expression using eval() and displays the result. If there’s an error (e.g., invalid syntax), it displays “Error.”

Clear (AC): Resets string and clears the display.

Delete (DEL): Removes the last character from string and updates the display.

Number and Operator Buttons: Adds the button’s value to string and updates the display.

Toggle Sign (+/-):

document.getElementById('plus_min').addEventListener('click', () => { ... })
Enter fullscreen mode Exit fullscreen mode

Multiplies the current number by -1 to toggle between positive and negative values.

Conclusively, building a simple yet functional calculator web app using HTML, CSS, and JavaScript is a fantastic project for both beginners and experienced developers. By carefully combining the structural foundation provided by HTML, the stylistic elements brought to life with CSS, and the interactive functionality powered by JavaScript, we can create an intuitive tool that not only serves its primary purpose but also demonstrates core web development concepts.

Moreover, this project opens up a wide range of possibilities for further exploration and enhancement. the lessons learned here provide a comprehensive foundation for more complex projects. Web development is an ongoing learning process, and this project showcases how every line of code contributes to a functional, engaging experience.

As you continue to refine your skills, consider how you can make this calculator even more user-friendly and powerful. Experiment with different layouts, try implementing additional mathematical functions. Every change you make deepens your understanding of coding principles and enhances your development resources.

Happy Coding!

Top comments (0)