Simple Calculator in HTML using for loops

When beginning to learn JavaScript, creating a calculator is often one of the initial tasks undertaken. In this guide, we will explore a straightforward approach to developing a basic calculator by leveraging HTML, CSS, and JavaScript. The tutorial will walk through the process of constructing a webpage housing a calculator by implementing for loops.

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.

One option is to utilize the eval function, although it is generally advised against due to potential security vulnerabilities. The eval function takes a string expression as an argument, processes it, and provides the output.

For example:

eval("4*3+2") returns 14

Nevertheless, it is advised to avoid utilizing eval due to its susceptibility to malicious exploits. As previously explained, eval has the capability to process expressions in various formats, including extensive strings. If an individual, whether a malicious hacker or a mischievous user, inputs an infinite value, the server can experience a significant slowdown as it continuously attempts to evaluate the expression instead of recognizing it as an attack.

Therefore, we will refrain from utilizing the function and instead rely solely on loops to construct a basic calculator.

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 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 different button types.

Customize the appearance of the calculator using CSS according to your preferences. To maintain simplicity, advanced styling options are not implemented. The calculator will be structured similarly to the one demonstrated in the tutorial that utilized eval for its functionality.

We'll make a calculator like this:

  • The code was created using io. Feel free to utilize any text editor or software of your choice for this purpose.

The HTML part:

  • 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: three empty columns, C and 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.
  • 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: three empty columns, C and 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 =.

The HTML part:

Code:

Example

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Calci</title>

</head>

<body>

   <center>

   <h1>Simple Calculator</h1>

   <table>

       <tr><input id = "display" size="38"></tr>

       <tr><td></td>

           <td></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> <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><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> <button onclick = fun(".")>.</button></td>

           <td> <button onclick = res()>=</button></td>

       </tr>

    </table>

    <p id="p"></p>

    <p id="p1"></p>

</center>

</body>

</html>

Output:

[visual]

  • When these buttons are pressed, there is no response observed.
  • Prior to delving into the styling aspect, we will focus on the functionality segment:

Now, it is time to design the web page using CSS:

CSS Part:

Example

<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 containing all CSS attributes 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.

JavaScript Part

It is time to give the actual functionality to the calculator using JavaScript:

  • 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 =.
  • 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.

The core functionality is centered around the function res. To begin, let's examine the following code:

Example

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

        var i, count=0;

        const index = [];

        const numbers = [];

        for(i=0;i<a.length;i++)

            {

                if(a[i]=="+" || a[i]=="-" || a[i]=="*" || a[i]=="/")

                    {

                        count+=1;

                        index.push(i);

                    }

            }

        document.getElementById("p").innerHTML="Indices of Operators: "+index;

        var j = 0;

        var num="";

        const res = [];

        var k = 0;

        for(i=0;i<a.length;i++)

            {

            if(i==0 && (a[0]=="-" || a[0]=="+"))

            {

                res[0]=0;

                j+=1;

                k+=1;

                continue;

            }

                if(j==index.length)

                    {

                        num+=a[i];

                        if(i==a.length-1)

                            {

                                res[k]=parseFloat(num);

                                break;

                            }

                    }

               else if(i==index[j])

                   {

                       j++;

                       res[k]=parseFloat(num);

                       num="";

                       k++;

                   }

                else{

                    num+=a[i];

                }

            }

        document.getElementById("p1").innerHTML="Operands:"+res;

        for(i=0;i<index.length;i++)

            {

                var j = 0;

                if(a[index[i]]=="/")

                    {

                        res[j] = res[j]/res[j+1];

                        res.splice(j+1, 1);

                    }

            }

        for(i=0;i<index.length;i++)

            {

                var j = 0;

                if(a[index[i]]=="*")

                    {

                        res[j] = res[j]*res[j+1];

                        res.splice(j+1, 1);

                    }

            }

        for(i=0;i<index.length;i++)

            {

                var j = 0;

                if(a[index[i]]=="+")

                    {

                        res[j] = res[j]+res[j+1];

                        res.splice(j+1, 1);

                    }

            }

        for(i=0;i<index.length;i++)

            {

                var j = 0;

                if(a[index[i]]=="-")

                    {

                        res[j] = res[j]-res[j+1];

                        res.splice(j+1, 1);

                    }

            }

         document.getElementById("display").value=a+"="+res;

        }

    </script>

Output:

Mechanism:

  • The expression typed on the display is stored in variable a .
  • Now, we created two arrays index and numbers .
  • Using a for loop, we traverse the expression to store the indices of operators into the array index and printed them in the paragraph defined in HTML.
  • So, the array index consists of the indices of the operators in a.
  • Now, we need to separate the expression which is in the form of a string into numbers using operators.
  • We create another array res.
  • Let us take an example to get it better: a = 8 + 9 - 8 * 23
  • Now, the array index = [1, 3, 5]
  • Suppose, the expression starts with a -, to handle that, we check if a[0] is - and if it is minus, we add a 0 to the expression at the start For example: -8-9 -> 0-8-9
  • In the for loop, we traverse the expression to fill res with values or numbers in a using index.
  • After getting the strings, we convert the values into floating numbers using parseFloat. We print that in the next paragraph.
  • Now, according to the above example: a = 8 + 9 - 8 * 23 index = [1, 3, 5] res = [8, 9, 8, 23]
  • See that the size of res = size of index - 1
  • We need to follow the mathematical rule BODMAS to solve any expression
  • If there is an expression like 3-25 3-10 = -7 should be the answer and not 15 = 5. Multiplication dominates subtraction
  • BODMAS: Brackets, Of, Division, Multiplication, Addition and Subtraction
  • There are no brackets in this calculator, so we just have to follow the four operators (Arithmetic - +, -, * and /)
  • Here, we used four for loops.
  • The idea is to traverse index and do the operations of operator at index[i] on res[j] and res[j+1]. To traverse index, we use i and j for traversing res.
  • splice is used to manipulate res after solving the operations. It pulls all the values to the empty indices with every empty index.
  • The first for loop does all the divisions, the second does the multiplications, third-> addition and the last one does the subtractions.
  • In the above example: a = 8 + 9 - 8 23 In the second loop: index = [1, 3, 5] res = [8, 9, 8, 23] a[index[2]] = res[1] = res[2]res[3] = 823 = 184 res = [8, 9, 184] In the third loop: index = [1, 3, 5] res = [8, 9, 184] a[index[0]] = + res[0] = res[0] + res[1] = 8 + 9 = 17 res = [17, 184] In the fourth loop: index = [1, 3, 5] res = [17, 184] a[res[1]] = 17 - 184 = -167 res = [-167]
  • Finally, we replace the expression on the display with the result.

Limitations:

  • This code can't handle , consecutive operators and isn't very efficient in terms of using more number of loops. This is just one of the thoughts we get to make a calculator.
  • We can extend the code into handling these. Observe that in the example we took, there is no / in the expression, but the first loop is just traversed without any use. Hence, this isn't a very efficient approach.
  • We'll see the best approach in the next tutorial called the " Shunting yard algorithm" by Dijkstra.

Input Required

This code uses input(). Please provide values below: