# Algorithm for Creating Calculator Using HTML, CSS, Javascript

Jul 25, 2023
Algorithm for Creating Calculator

Welcome to our exciting journey into the world of web development. In this article, we are going to create a project using HTML, CSS, and JavaScript. We will provide the code where you can see the algorithm behind the calculator. There are algorithms for creating a calculator using HTML, CSS, and JavaScript. HTML and CSS provide the frontend part, and JavaScript works as a backend. With the help of both, we are going to create our first project. But hold on, before we write 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. Let’s get ready to build our very first calculator project!

## Building a custom Calculator with HTML, CSS, Javascript

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>
<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">1</button>
<button class="button">2</button>
<button class="button">3</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">7</button>
<button class="button">8</button>
<button class="button">9</button>
<button class="button">*</button>
</div>
<div class="row">
<button class="button">AC</button>
<button class="button">0</button>
<button class="button">=</button>
<button class="button">/</button>
</div>
</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.
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. `<link rel="stylesheet" href="style.css">`: This line links an external CSS file named `style.css` to the HTML document. This CSS file defines the visual appearance and layout of the calculator.
8. `<link rel="stylesheet" href="utils.css">`: This line links another external CSS file named `utils.css` to the HTML document. This CSS file contains additional styles for layout and alignment of elements on the calculator web page.
9. `<body>`: The body section contains the visible content of the web page.
10. `<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.
11. `<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.
12. `<div class="row">`: This line defines a row of buttons in the calculator. Each row contains four buttons.
13. `<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.
14. `<button class="button">`: These are the buttons for the calculator. Each button has a class `button` for styling.
15. `<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.

### Script.js

This JavaScript code is 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) => {
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 explain 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.

### 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;
}``````

Explanation of Code

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;
}``````

Explanation of Code:

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

The provided code consists of an HTML document for a simple calculator web page, along with 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 appropriate spacing, borders, and alignment.

To create a fully functional calculator, additional JavaScript logic is required to handle operator precedence, input errors, and other calculator features, such as memory functions and scientific calculations. Further enhancements could include improving responsiveness for different devices and adding ARIA attributes for screen readers.

#### By Anshul Pal

Hey there, I'm Anshul Pal, a tech blogger and Computer Science graduate. I'm passionate about exploring tech-related topics and sharing the knowledge I've acquired. With two years of industry expertise in blogging and content writing, I'm also the co-founder of HVM Smart Solution. Thanks for reading my blog – Happy Learning!