Build A Calculator With JavaScript

Mastering Web Development Fundamentals by Creating a Dynamic Calculator

Hello, future web developer! Are you prepared to explore the world of web programming and build something entertaining and useful?

In this lesson, I'll teach you how to create a straightforward calculator using HTML for structure, CSS for design, and JavaScript for functionality. The calculator will also be able to carry out the following operations: clear and delete operations, multiplication, division, percentage calculations, and addition and subtraction.

Prerequisites

HTML: Understanding HTML, especially its components, properties, and their placement inside HTML documents, is crucial.

To understand how the calculator is styled, you must have a basic understanding of CSS (Cascading Style Sheets). Selectors, properties, values, and fundamental style principles are included in this.

JavaScript Foundations: Readers should have a basic understanding of JavaScript principles such as variables, data types, functions, conditional expressions (if-else), loops, and event handling (addEventListener).

Table of Contents

Introduction

Creating the HTML Structure

CSS styling

Using JavaScript to Control Calculator Functionality

Conclusion

INTRODUCTION

Building a calculator in HTML, CSS, and JavaScript is a helpful method for improving your JavaScript abilities. In this session, we'll show you how to build a simple calculator that you can use as the starting point for more difficult projects. CSS will be used to style the calculator, HTML to structure it, and JavaScript to include interactive elements. I'm here to guide you through the procedure step by step and make sure you enjoy yourself while doing it. So grab a seat and prepare to learn how to build a calculator from the ground up!

Creating the HTML Structure

We begin by establishing the fundamental HTML structure for our calculator. We'll define the display area and buttons for each number and operation. The structure is demonstrated by the code example below:

<div class="container">

    <input type="text" class="display" />

    <div class="buttons">

<!-- Buttons for numbers and operations -->
        <button data-value="AC">AC</button>
        <button data-value="DEL">DEL</button>
        <button data-value="%">%</button>
        <button data-value="/">/</button>

        <button data-value="7">7</button>
        <button data-value="8">8</button>
        <button data-value="9">9</button>
        <button data-value="*">*</button>

        <button data-value="4">4</button>
        <button data-value="5">5</button>
        <button data-value="6">6</button>
        <button data-value="-">-</button>

        <button data-value="1">1</button>
        <button data-value="2">2</button>
        <button data-value="3">3</button>
        <button data-value="+">+</button>

        <button data-value="0">0</button>
        <button data-value="00">00</button>
        <button data-value=".">.</button>
        <button data-value="=">=</button>
      </div>

</div>

The dataset is a custom property that enables you to store additional information associated with the button element in button. Although these components cannot be visible on the webpage itself, JavaScript can be used to obtain and modify this data.

CSS Styling

The given CSS code snippet is in charge of customizing the calculator's look and making sure that the user interface is aesthetically pleasing. Let's examine the many stylistic elements and how they influence the final product.

Universal Styling

The snippet of code below establishes general stylistic guidelines that are applied to all page elements:

* {

padding: 0;

margin: 0;

box-sizing: border-box;

}

/*Display Area Styling*/

.display {

width: 80%;

border: none;

padding: 40px 0;

color: white;

background-color: rgb(31, 27, 27);

font-size: 60px;

text-align: right;

overflow: hidden;

}

/*Container Styling*/

.container {

margin: 0 auto;

height: 100vh;

display: flex;

flex-direction: column;

align-items: center;

justify-content: flex-end;

min-width: 300px;

background-color: rgb(31, 27, 27);

max-width: 400px;

}

/*Button Styling*/

.buttons button {

font-size: 25px;

background-color: rgb(239, 244, 248);

margin: 0 auto;

display: flex;

align-items: center;

justify-content: center;

border: none;

border-radius: 50%;

width: 80px;

height: 80px;

}

/*Button Hover and Focus Styling*/

.buttons button:hover,

.buttons button:focus {

background: rgb(70, 69, 69);

color: aliceblue;

}

The calculator ux

Using JavaScript to Control Calculator Functionality

"use strict";

const display = document.querySelector('.display');

const buttons = document.querySelectorAll('.buttons button');

We start creating code in JavaScript using the "use strict" directive, which enforces better coding standards and tougher error handling.

The code initializes variables to communicate with the HTML document's structure, known as the Document Object Model (DOM).

//Step 1: Add event listener to the button, call calculator() on click

buttons.forEach((button) => {

//step 2: button click listener calls calculator() with dataset value as argument.

button.addEventListener("click", e => calculate(e.target.dataset.value));

})

Each button element in the calculator interface is iterated by using the code segment buttons.forEach((button) => {}. An event listener is created for each button to react to a "click" event. A button's connected arrow function is called when it is clicked, receiving the event object as an argument.

This function uses the 'e.target.dataset.value' variable to extract the 'data-value' property of the clicked button, which represents the particular action or number associated with the button. By allowing the execution of relevant actions based on the value of the button that was pressed, this strategy facilitates user input's interaction with the calculator's functionality.

//Step3: Define the function to calculate based on the button clicked

const calculate = (btnValue) => {

}

Calculate is the name of a JavaScript function. The logic of the calculations will be handled by this function in accordance with the button that has been pressed on the calculator interface. The value related to the clicked button is represented by an argument named btnValue, which the function takes.

Step 4: Create an array of special characters

const specialChars = ["%", "*", "/", "+", "="];

To denote certain operations, the calculator will use a set of special characters from an array named "specialChars". These include the following symbols: percentage (%), plus (+), slash (/), and equals (=). This array will be used to analyze button clicks and select the appropriate replies for each special character.

Step 5: Make the 'output' empty

let output = "";

The variable 'output' is defined and initialized with an empty string as its value. This variable will be used to store the current input as well as any intermediate computation results that are presented on the calculator's screen. When users interact with the calculator by clicking buttons, the 'output' variable is modified, reflecting the input and calculations that are presently being done.

const calculate = (btnValue) =>

//Step 6: make the display value output

display.value = output;

}

The calculated result or modified input is given the value specified by 'display.value'.

The 'display' variable refers to the HTML input element that represents the calculator's display area. By setting the calculator's 'value' property to the value stored in the 'output' variable, the most recent input, intermediate calculation results, or final result are displayed on the screen.

The 'btnValue' parameter, which is handled by the 'calculate' method, represents the value associated with the button that was clicked in the calculator interface. This portion of the code ensures the calculator's functionality by including the logic that carries out various operations depending on the value of the button that was clicked.

Step 7: Handling the Equals Button ('=')

const calculate = (btnValue) => {

if(btnValue == "=" && output !== "") {

output = eval(output.replace("%", "/100"))

}

This step checks to see whether the output variable is not empty and if the clicked button's value is "=." If the required conditions are met, the calculator runs the eval function to evaluate the stored mathematical equation. Before evaluation, any % symbols in the output that relate to percentage calculations are converted to /100.

Step 8: Clear All ('AC')

}else if (btnValue === "AC") {

output = "";

}

If the value of the button that was pressed is "AC," the output variable is cleared, resetting the calculator's state.

Step 9: Delete ('DEL')

else if (btnValue === "DEL") {

output = output.toString().slice(0, -1);

}

If the clicked button's value is 'DEL', It simulates a backspace action by removing the last character from the output.

Else: Regular Number and Operation Inputs

else {

if (output === "" && specialChars.includes(btnValue))

return;

output += btnValue;

}

If none of the previous conditions are true, this section of the code deals with regular numbers and operation inputs.

It checks to see if the output is empty or if the btnValue is a special character. If so, it stops you from entering a string of special characters after another.

If not, it increases the output by the value of the button that was clicked.

CONCLUSION

You will be better able to analyze complex web development issues if you have a firm grasp of these basic concepts. This training strengthens your front-end programming skills and lays the groundwork for creating engaging and dynamic web applications. You are welcome, Happy coding with Awwal!