Creating a calculator is often one of the initial tasks tackled when delving into HTML and JavaScript. This guide will walk you through a basic approach to crafting a straightforward calculator utilizing HTML, CSS, and JavaScript. Our goal is to establish a basic webpage housing a functional calculator.
Simple Introduction to HTML, CSS and JS:
- HTML is the markup language used to structure a webpage.
- CSS is the styling language used to design the layout and look of the elements of the webpage.
- JS is the scripting language used to define the behavior and working of the elements in the webpage.
eval method:
The eval function takes a string expression as an argument, processes it, and then outputs the evaluated result.
For example:
eval("4*3+2") returns 14
However, the utilization of eval is discouraged due to its potential for malicious exploitation. As mentioned earlier, eval has the capability to process expressions in various formats, including extensive strings. If provided with an infinite value by a malicious user, such as a hacker, the function will continuously execute, causing a significant slowdown of the server as it tirelessly attempts to assess the expression rather than recognizing the attack.
It is crucial to acknowledge that employing eval can pose a security risk. When a program accepts user input that is subsequently fed into eval, there exists a vulnerability where a hacker could introduce malevolent code as input. This rogue code could then execute unrestricted within the function's scope, compromising sensitive information like login credentials.
To mitigate these risks, it is imperative to sanitize the input utilized by the eval function. Alternatively, considering the substitution of eval with a more secure function is advisable.
We will utilize a basic calculator design suitable for novice users.
Idea:
The idea is to create a table. The first row of the table should be the display. The next rows must contain buttons of numbers, clear, Back space, equals to and operators.
- On clicking numbers or operators, the value of the button must be displayed on the display.
- On clicking on C, the display has to become empty.
- On clicking B, the last element on the display must be deleted.
- On clicking =, everything on the display must be solved using eval and now the display has to show the result of the expression entered.
Therefore, it is necessary to create four JavaScript functions to handle the operations of the four distinct button types. The design of the calculator can be customized using CSS according to your preferences. In this case, we will opt for a straightforward approach without incorporating extensive styling elements.
We'll make a calculator like this:
- The code was created using io. Feel free to utilize a text editor or any preferred software of your choice for this purpose.
- Create a new file with .html extension: calci.html
- In the head, we've given the title as calci. The first tag in body is center, to place the heading and the calculator in the middle of the web page.
- Then, we gave the main heading of the web page as "Simple Calculator".
- We constructed a table, such that:
- Every row consists of buttons to be pressed and on every button click, a function from js is called for the calculation.
- Buttons in the first row: 0, (, ), empty column, C, B. C is for clearing the display and B is for giving a back space.
- Buttons in the second row: 7, 8, 9, empty column, +, and -.
- Buttons in the third row: 6, 5, 4, empty column, *, and /.
- Buttons in the fourth row: 1, 2, 3, empty column, decimal point and =.
- We'll be using inline CSS and js in the head section with <style></style> and <script></script> tags.
The HTML part:
Here is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calci</title>
<script type = text/javascript></script>
<style></style>
</head>
<body>
<center>
<h1>Simple Calculator</h1>
<table>
<tr><input id = "display"></tr>
<tr><td> <button onclick = fun(0)>0</button></td>
<td> <button onclick = fun("(")>(</button></td>
<td> <button onclick = fun(")")>)</button></td>
<td></td>
<td> <button onclick = C()>C</button></td>
<td> <button onclick = B()>B</button></td>
</tr>
<tr><td> <button onclick = fun(7)>7</button></td>
<td> <button onclick = fun(8)>8</button></td>
<td> <button onclick = fun(9)>9</button></td>
<td></td>
<td> <button onclick = fun("+")>+</button></td>
<td> <button onclick = fun("-")>-</button></td>
</tr>
<tr><td> <button onclick = fun(6)>6</button></td>
<td> <button onclick = fun(5)>5</button></td>
<td> <button onclick = fun(4)>4</button></td>
<td></td>
<td><button onclick = fun("*")>*</button></td>
<td><button onclick = fun("/")>/</button></td>
</tr>
<tr><td> <button onclick = fun(1)>1</button></td>
<td> <button onclick = fun(2)>2</button></td>
<td> <button onclick = fun(3)>3</button></td>
<td></td>
<td> <button onclick = fun(".")>.</button></td>
<td> <button onclick = res()>=</button></td>
</tr>
</table>
</center>
</body>
</html>
Output:
[visual]
Upon clicking these buttons, there is no response.
Prior to delving into the design aspect, we will focus on the operational aspect:
JavaScript Part:
- We've already discussed about the eval function. After taking the input from the user, we'll give the expression as input to the function.
- Observe the HTML code, we've called four functions fun, C, B and res.
- fun(a): On clicking all the buttons of numbers and operators, we call fun with the value of the number or operator as argument. In the function, we need to print that value on the display input box, hence, we concatenate the argument to the value already in the input box.
- C: We'll simply reassign the value of the display input box to an empty string to clear the display.
- B: We'll get the whole string on the display and slice it deleting the last element and re-assign it to the display again.
- res: This function is activated on clicking =. We'll just get the whole expression on the display and pass it as an argument to eval and reassign the result to the display.
- On clicking all the buttons of numbers and operators, we call fun with the value of the number or operator as argument.
- In the function, we need to print that value on the display input box, hence, we concatenate the argument to the value already in the input box.
Inline JS Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calci</title>
<script type = text/javascript>
function fun(a)
{
document.getElementById("display").value+=a;
}
function C()
{
document.getElementById("display").value = "";
}
function B()
{
var y = document.getElementById("display").value;
document.getElementById("display").value = y.slice(0, y.length-1);
}
function res()
{
var a = document.getElementById("display").value;
document.getElementById("display").value=a+"="+eval(a);
}
</script>
Output:
Now, it is time to design the web page using CSS:
CSS Part:
<style>
table {
background-color: brown;
border: 1px solid black;
table-layout: fixed;
border: 1px solid black;
border-spacing: 10px;
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
border-radius: 10px;
}
button{
padding: 16px;
border-radius: 8px;
}
button:hover{
background-color: black;
color: white;
}
button:active{
transform: scale(0.98);
box-shadow:3px 2px 22px 1px rgba(0, 0, 0, 0.24);
}
#display{
width:290px;
height:40px;
margin: 10px 0;
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
border-radius: 10px;
}
#display:hover{
background-color: black;
color: white;
}
body{
background-color: black;
}
h1{
color: white;
}
body:hover{
background-color: floralwhite;
}
body:hover h1{
color: black;
}
</style>
Below is a comprehensive table listing various CSS properties along with detailed explanations:
Table styling:
| Property | Explanation |
|---|---|
| table_layout: fixed | The layout of all the cells in the table remains fixed (Width of the columns) irrespective of the length of content inside. |
| border-spacing: 10px | Distance or space between the borders of cells. It applies only when border-collapse is set to separate. We can set both vertical and horizontal distances. |
| box-shadow | To attach a shadow to an element. We can add multiple shadows to a single element by separating them by a comma. |
| border-radius | To curve the edge of the element's corners. (To add rounded corners to an element). The greater the value, rounder the corner will be. We can give four values to four corners. |
| background-color | The color to the background of an element. We can give the name of the color or use hexadecimal codes. |
| border | One property for adding the width, style and color to the borders of an element. |
Button:
| Property | Explanation |
|---|---|
| padding | To create space between the element and the border around it. Using padding-top, padding-right, padding-bottom and padding-left, we can give spaces on each side of the element. |
| border-radius | To curve the edge of the element's corners. (To add rounded corners to an element). The greater the value, rounder the corner will be. We can give four values to four corners. |
| hover: background-color | Using element:hover, we can add a property to the element when user hovers (moves) the cursor on the element. Here, we are changing the background color. |
| color | Font color. |
| active: tranform | Using element:active, we can add a property to the element when user clicks on the element. Transform is used to add 2D effects to the elements. Here, we are using scale(). This function can resize the element and then back to the original size. We used this to get a button effect when pressed. |
| body: hover h1{} | When user hovers on the body, we can change the property of h1 using this syntax. |