# Algorithm for Creating Calculator Using HTML, CSS, Javascript by – APalgorithm

25 July 2023

Welcome to our exciting journey into the world of web development. In this article we are going to create a project using html, CSS & JavaScript. We provided the code where you can see the algo behind the calculator. There are algorithms for creating a calculator using HTML, CSS and Javascript. Where html and CSS provide the frontend part and JavaScript work as a backend, by the help of both we are going to create our first project. But hold on, before we dive into code and algorithms, let’s acknowledge that building a calculator isn’t confined to a single route. While we’ll present a particular approach here, it’s essential to remember that there are countless ways to tackle this challenge. So, grab your coding gear, fasten your seatbelt, and let’s get ready to build our very first calculator project! Along the way, we’ll uncover the magic behind user interaction, reveal the secrets of arithmetic algorithms, and explore the art of front-end and back-end collaboration. Let the coding adventure begin!

# Algorithm for Calculator

The provided code is an HTML document for a simple calculator web page. It creates a basic calculator interface with buttons for digits, arithmetic operators, and some special buttons like AC (All Clear), %, (, ), and =.

### index.html

```<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Your Calculator! - First Choice Calculator</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="utils.css" rel="stylesheet" type="text/css" />
<body>
<h1 class="text-center">Welcome to my Calculator</h1>
<div class="container flex flex-col items-center  mx-auto m-w-20">
<div class="row">
<input class="input" type="text">
</div>
<div class="row">
<button class="button">AC</button>
<button class="button">%</button>
<button class="button">(</button>
<button class="button">)</button>
</div>
<div class="row">
<button class="button">7</button>
<button class="button">8</button>
<button class="button">9</button>
<button class="button">*</button>
</div>
<div class="row">
<button class="button">4</button>
<button class="button">5</button>
<button class="button">6</button>
<button class="button">/</button>
</div>
<div class="row">
<button class="button">1</button>
<button class="button">2</button>
<button class="button">3</button>
<button class="button">+</button>
</div>
<div class="row">
<button class="button">0</button>
<button class="button">.</button>
<button class="button">=</button>
<button class="button">-</button>
</div>
<script src="script.js"></script>
</body>
</html>```

Explanation of code –

1. `<!DOCTYPE html>`: This line specifies the document type and version of HTML being used (HTML5 in this case).
2. `<html>`: The root element of the HTML document.
3. `<head>`: The head section contains meta-information about the document and links to external resources like CSS and JavaScript files.
4. `<meta charset="utf-8">`: This meta tag specifies the character encoding for the document, which is set to UTF-8, a common character encoding that supports a wide range of characters from various languages.
5. `<meta name="viewport" content="width=device-width">`: This meta tag sets the viewport width to the device width, which is crucial for responsive design on different devices.
6. `<title>Your Calculator! - First Choice Calculator</title>`: This line sets the title of the web page, which will be displayed in the browser’s title bar or tab.
7. CSS Styling: The two lines with `<link>` elements are used to link external CSS files (`style.css` and `utils.css`) to the HTML document. These CSS files define the visual appearance and layout of the calculator.
8. `<body>`: The body section contains the visible content of the web page.
9. `<h1 class="text-center">Welcome to my Calculator</h1>`: This line displays a centered heading “Welcome to my Calculator” at the top of the page.
10. `<div class="container flex flex-col items-center mx-auto m-w-20">`: This is the main container that holds the calculator layout. It uses CSS classes like `flex`, `flex-col`, `items-center`, `mx-auto`, and `m-w-20` to style and position the elements within the container.
11. `<div class="row">`: This line defines a row of buttons in the calculator. Each row contains four buttons.
12. `<input class="input" type="text">`: This input element is used to display the user’s input and the calculator’s result. It has a class `input` to apply specific styles.
13. `<button class="button">`: These are the buttons for the calculator. Each button has a class `button` for styling.
14. `<script src="script.js"></script>`: This line includes an external JavaScript file named `script.js`, which likely contains the logic for handling button clicks and performing calculations.

Note: While the HTML structure and basic elements of the calculator are provided, the actual functionality and calculations are most likely implemented in the referenced `script.js` file, which is not included here. The calculator’s behavior would depend on the JavaScript code in that file.

To make the calculator fully functional, you would need to implement the necessary JavaScript functions to handle button clicks, process the user’s input, and display the calculated result on the input field.

### script.js

This JavaScript codeis an event listener that handles button clicks for the calculator. It utilizes the `eval()` function to evaluate and compute the mathematical expression stored in the `string` variable and then updates the calculator’s input field accordingly.

```let string = "";
let buttons = document.querySelectorAll('.button');
Array.from(buttons).forEach((button) => {
button.addEventListener(`click`, (e) => {
if (e.target.innerHTML == '=') {
string = eval(string);
document.querySelector(`input`).value = string;
}
else if (e.target.innerHTML == 'AC') {
string = "";
document.querySelector(`input`).value = string;
}
else {
console.log(e.target)
string = string + e.target.innerHTML;
document.querySelector(`input`).value = string;
}
})
})```

Let’s break down the code:

1. `let string = "";`: This initializes a variable called `string` and sets it to an empty string. This variable will be used to store the user’s input, which represents the mathematical expression.
2. `let buttons = document.querySelectorAll('.button');`: This line selects all elements with the class `button` and stores them in the `buttons` variable. These elements correspond to the calculator buttons.
3. `Array.from(buttons).forEach((button) => { ... })`: This converts the NodeList obtained from `document.querySelectorAll` into an array and then iterates over each button using the `forEach` method.
4. `button.addEventListener('click', (e) => { ... })`: This adds a click event listener to each button, so when any of the calculator buttons is clicked, the provided callback function will be executed.
5. `if (e.target.innerHTML == '=') { ... }`: This condition checks if the clicked button’s innerHTML (the text inside the button) is equal to ‘=’. If it is, the code inside the corresponding block will be executed.
6. `string = eval(string);`: The `eval()` function takes the string stored in the `string` variable, evaluates it as a mathematical expression, and assigns the result back to the `string` variable. For example, if `string` contains “2+3”, `eval(string)` will return 5.
7. `document.querySelector('input').value = string;`: This updates the value of the input field with the calculated result (stored in the `string` variable).
8. `else if (e.target.innerHTML == 'AC') { ... }`: This condition checks if the clicked button’s innerHTML is equal to ‘AC’, indicating the “All Clear” button was clicked.
9. `string = "";`: If ‘AC’ is clicked, the `string` variable is reset to an empty string.
10. `else { ... }`: If none of the previous conditions are met, it means a digit or operator button was clicked.
11. `string = string + e.target.innerHTML;`: The clicked button’s innerHTML (digit or operator) is appended to the existing `string` variable.
12. `document.querySelector('input').value = string;`: The input field is updated to show the current `string` value, which is the updated mathematical expression.

This code assumes that the HTML structure for the calculator is as previously provided, with buttons having their respective numbers and operators as innerHTML.

It’s important to note that using `eval()` to evaluate user input can be risky and may lead to security vulnerabilities (such as code injection attacks). It’s generally recommended to implement a safer way to parse and evaluate mathematical expressions, such as using a library like math.js or writing a custom parser.

### style.css

The CSS code provided contains the styles for the calculator’s buttons and input field.

```.button{
width: 66px;
margin: 0 3px;
border: 2px solid black;
cursor: pointer;
}
.row{
margin:8px 0;
}
.row input{
font-size: 20px;
margin: 0;
border: 2px solid black;
}```

Let’s break down each part:

1. `.button { ... }`: This style block applies to elements with the class `button`, which correspond to the calculator buttons.
• `width: 66px;`: Sets the width of the button to 66 pixels.
• `padding: 20px;`: Adds 20 pixels of padding around the content inside the button, making it visually larger.
• `margin: 0 3px;`: Sets a margin of 0 pixels on the top and bottom and 3 pixels on the left and right sides, creating spacing between the buttons.
• `border: 2px solid black;`: Applies a black solid border with a width of 2 pixels around the button.
• `border-radius: 9px;`: Sets the border radius to 9 pixels, giving the buttons rounded corners.
• `cursor: pointer;`: Changes the mouse cursor to a pointer when hovering over the button, indicating it is clickable.
2. `.row { ... }`: This style block applies to elements with the class `row`, which represent the rows of buttons in the calculator.
• `margin: 8px 0;`: Sets a margin of 8 pixels on the top and bottom, creating vertical spacing between rows of buttons.
3. `.row input { ... }`: This style block applies to the input element within the rows. The input element is used to display the user’s input and the calculator’s result.
• `font-size: 20px;`: Sets the font size of the text inside the input field to 20 pixels.
• `margin: 0;`: Sets the margin of the input field to 0 pixels, removing any extra spacing around it.
• `padding: 10px 0px;`: Adds 10 pixels of padding on the top and bottom of the input field, creating vertical spacing between the input field and the rows of buttons.
• `border: 2px solid black;`: Applies a black solid border with a width of 2 pixels around the input field.
• `border-radius: 5px;`: Sets the border radius to 5 pixels, giving the input field rounded corners.

Overall, these styles make the calculator buttons and input field visually appealing with proper spacing and border designs. However, it’s essential to ensure that the rest of the CSS (style.css and utils.css) is properly implemented to achieve the desired look and functionality of the calculator web page.

### utils.css

The CSS code provided contains additional styles that are used to define layout and alignment for elements on the calculator web page.

```.text-center{
text-align: center;
}
.bg-red{
background-color: red;
}
.mx-auto{
margin: auto;
}
.flex{
display: flex;
}
.flex-col{
flex-direction: column;
}
.items-center{
align-items: center;
}```

Let’s break down each part:

1. `.text-center { ... }`: This style block applies to elements with the class `text-center` and centers the text horizontally within those elements.
• `text-align: center;`: Sets the horizontal alignment of the text to center within the element.
2. `.bg-red { ... }`: This style block applies to elements with the class `bg-red` and sets their background color to red.
• `background-color: red;`: Sets the background color of the element to red.
3. `.mx-auto { ... }`: This style block applies to elements with the class `mx-auto` and centers them horizontally within their parent container.
• `margin: auto;`: Sets the left and right margins of the element to “auto,” which centers the element horizontally within its parent container.
4. `.flex { ... }`: This style block applies to elements with the class `flex` and turns them into a flex container.
• `display: flex;`: Sets the element’s display property to “flex,” enabling flexbox layout.
5. `.flex-col { ... }`: This style block applies to elements with the class `flex-col` and changes their flex-direction to “column.”
• `flex-direction: column;`: Sets the flex container’s main axis to be vertical, making the flex items stack in a column.
6. `.items-center { ... }`: This style block applies to elements with the class `items-center` and aligns their items (children) vertically at the center within the flex container.
• `align-items: center;`: Aligns the flex items vertically at the center.

These styles are likely used in combination with the HTML structure provided earlier to define the layout and alignment of the calculator’s elements, creating a visually appealing and centered calculator interface. The styles help in positioning the calculator’s elements correctly, such as centering the buttons and the input field within their respective containers and ensuring that they are aligned nicely on the page.

## Conclusion

In conclusion, the provided code consists of an HTML document for a simple calculator web page along with some JavaScript and CSS code to handle button clicks and style the calculator interface. The calculator allows users to input mathematical expressions using the provided buttons and then calculates the result using the `eval()` function. The CSS styles make the calculator buttons and input field visually appealing with proper spacing, borders, and alignment.

However, it’s important to note that using `eval()` to evaluate user input can be risky and may lead to security vulnerabilities. It’s generally recommended to implement a safer way to parse and evaluate mathematical expressions, such as using a library like math.js or writing a custom parser.

In practice, this code snippet serves as a foundation for building a basic calculator web page. To create a fully functional calculator, additional JavaScript logic would be needed to handle operator precedence, handle input errors, and implement other calculator features like memory functions, scientific calculations, etc.

Additionally, to provide a better user experience and improve the accessibility of the calculator, further enhancements could be made in terms of responsiveness for different devices and the inclusion of ARIA attributes for screen readers.

Overall, with the right improvements and enhancements, this code can be a good starting point for creating a functional and visually appealing calculator application on the web.