Make your own calculator in HTML, CSS, JAVASCRIPT

April 14, 2020

This post was featured on The Startup in 2020. Check it out here.

Hey, what’s up, everyone!

Today, we’ll be making our own calculator using HTML, CSS & JAVASCRIPT.

This project is divided into 2 parts: The Front End & The Back End. We’ll be making the structure of our Calculator using HTML and beautifying it using CSS in the Front end part.

In the Back End part, we’ll be giving it life, i.e will make it work to solve the equations. The back end part will be done using javascript.

Our final project will look like this:

https://kcldtzblfykiwwltfouv.supabase.co/storage/v1/object/sign/meta/1__zezo__lSBZmvNIrfQkUPYRw.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJtZXRhLzFfX3plem9fX2xTQlptdk5JcmZRa1VQWVJ3LnBuZyIsImlhdCI6MTY2MzY3Mjk4NywiZXhwIjoxOTc5MDMyOTg3fQ.QuIJ_9KVNRa43znPRWFiEfMjkef9smYPC5ejMq2ema4&t=2022-09-20T11%3A23%3A07.207Z

So let’s dive into Part 1: The structure and design of our calculator.

First, open your desired code editor. In my case, I’d be using VS Code. You may use anyone you like (Sublime Text, Atom etc.). Don’t use Notepad, please.

First, save the new file as “*projectname*.html”. After this, we’ll be adding the basic structure of our HTML file (the boilerplate). In VS Code, you can get it by typing “!” and hitting enter, while in sublime text, you get it by typing “<html” and pressing enter. Now you’ll see something like this:

https://kcldtzblfykiwwltfouv.supabase.co/storage/v1/object/sign/meta/1__IeKYvDwiG9PaSuFET__ihTw.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJtZXRhLzFfX0llS1l2RHdpRzlQYVN1RkVUX19paFR3LnBuZyIsImlhdCI6MTY2MzY3MzAxOCwiZXhwIjoxOTc5MDMzMDE4fQ.B9oHqxk72xCJIMOdCzH9d-Sh0f7-sYaMQz8e1lWwoeM&t=2022-09-20T11%3A23%3A38.830Z

Change the text “Document” with the name you want to give to your Calculator Project.

Now, we have to define an area where we’ll be showing the output to the user. This is our output screen. For that, I’m making a division with class display.

<div class="display"></div>

Now, this display (output) screen has to show some text even before the user inputs some equation to solve. For that, we’ll be using 0. So let’s make a paragraph inside the “display” division with default-text 0 :

<p id="output">0</p>

Now, below the output screen, we have our first row of buttons. Different calculators have different kinds of buttons arrangement. So I’m using the button arrangement with which I’m comfortable. You can use your set of button arrangements once you’re clear with how to make this project.

Our first row of buttons will have 3 buttons, although the next row will have 4 buttons. This is because the Clear button in the first row will take place of 2 buttons as it’s the primary button in our calculator (0 as well). You might have seen that in the screenshot above as well.

https://kcldtzblfykiwwltfouv.supabase.co/storage/v1/object/sign/meta/1__1fgBg3ti6RCHTBtfrln__UA.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJtZXRhLzFfXzFmZ0JnM3RpNlJDSFRCdGZybG5fX1VBLnBuZyIsImlhdCI6MTY2MzY3MzA0OSwiZXhwIjoxOTc5MDMzMDQ5fQ.kP5Oteu6SKqSweOkXHqsjzpgsD6Z1NM0M0UGkqUaLN8&t=2022-09-20T11%3A24%3A09.932Z

For this, I’m defining a new div with class “first-row”. Here all our buttons belonging to the first row will be placed here. The buttons will be “C” , “%” & “/”.

<div class="first-row"> </div>

Inside this div, we’ll place our buttons. Buttons are inserted using <button> tag, followed by </button>. The text that our button should hold is placed between these two tags. Along with the buttons, we’ll be giving them an id. This id will help us at the time of back end programming.

The id should follow the format: “row_no-button_no”. For example: if the button is for row 1 and is the first button in the row, it will have an id “r1–1”.

See example below

<button id="r1-1">C</button>

Now, I’m assuming you can make the basic structure of your calculator on your own.

Your calculator by this time should look like this:

https://kcldtzblfykiwwltfouv.supabase.co/storage/v1/object/sign/meta/1__KUjDzpdSiFTEm66c__0fskA.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJtZXRhLzFfX0tVakR6cGRTaUZURW02NmNfXzBmc2tBLnBuZyIsImlhdCI6MTY2MzY3MzA3NywiZXhwIjoxOTc5MDMzMDc3fQ.XNidFZkVj6NflHuogPU9I_fvGw0xlxqp4V0FTUALk2U&t=2022-09-20T11%3A24%3A37.989Z

If you’re not getting stuff like the above, refer to the given HTML. Don’t just copy-paste it). If you got everything perfect, cheers.

<p id="output">0</p>

<div class="first-row">
   <button id="r1-1">C</button>
   <button id="r1-3">%</button>
   <button id="r1-4">/</button>
</div>

<div class="second-row">
   <button id="r2-1" >7</button>
   <button id="r2-2" >8</button>
   <button id="r2-3" >9</button>
   <button id="r2-4" >X</button>
</div>

<div class="third-row">
   <button id="r3-1" >4</button>
   <button id="r3-2" >5</button>
   <button id="r3-3" >6</button>
   <button id="r3-4" >-</button>
</div>

<div class="fourth-row">
   <button id="r4-1"  >1</button>
   <button id="r4-2"  >2</button>
   <button id="r4-3"  >3</button>
   <button id="r4-4"  >+</button>
</div>

<div class="fifth-row">
  <button id="r5-1" >0</button>
  <button id="r5-2" >.</button>
  <button id="r5-3" >=</button>
</div>

Clicking any button at this time would not do anything. There’s a lot way to go.

But the calculator is looking ugly. Let’s jump to CSS section.

Remember the calculator will not be responsive as it would have taken more time to explain. So once you’re able to understand this simple coding process, you can go ahead in making the calculator responsive.

So you have to connect the new CSS file (say “style.css”) to the HTML page.

For that, inside the head tag, the below code has to be there:

<link rel="stylesheet" href="style.css" type="text/css">

Now, we have to design the output screen, to which we gave the class as “.display”.

https://kcldtzblfykiwwltfouv.supabase.co/storage/v1/object/sign/meta/1__PyiDvolwaSDGoXU4__dH60w.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJtZXRhLzFfX1B5aUR2b2x3YVNER29YVTRfX2RINjB3LnBuZyIsImlhdCI6MTY2MzY3MzEwMCwiZXhwIjoxOTc5MDMzMTAwfQ.2IPFqTj62RVfpQZMsZ1Yf-dWOasS9ZVN-paeFd4W9co&t=2022-09-20T11%3A25%3A01.029Z

We have to make it look like the above snapshot.

So 5 things will be involved in making the output screen like that.

  1. Its background-colour
  2. Padding
  3. Width
  4. Text alignment
  5. Font size

BONUS: THE BORDER RADIUS CAN BE CHANGED TO MAKE IT LOOK GOOD.

So let's write our CSS code for this:

.display {
      background-color: rgb(201, 201, 201);
      padding: 15px;
      width: 250px;
      text-align: right;
      font-size: 20px;
      border-top-left-radius:10px;
      border-top-right-radius:10px;
}

The text has to be aligned to the right because most calculators have arrangements like that only.

Congrats, you’ve made your output screen look good.

Now, we’ll be writing common CSS code for all the buttons, as we want them to look similar. (except 0 & C, we’ll get back to them).

It’ll involve 7things:

  1. Padding
  2. Width
  3. Height
  4. Margin
  5. Background colour
  6. Text colour
  7. Font size

You can customize all the above properties as per your own creativity.

button {
      padding: 10px;
      width: 67px;
      height: 45px;
      margin-top: 10px;
      background-color: rgb(194, 194, 194);
      color: black;
      font-size: 20px;
}

Now, let's go-to style 0 & C buttons. They require a width of two buttons. We have to go to the HTML section and style them manually.

Refer to the code:

<button id="r1-1" style="width: 138px;">C</button>
<button id="r5-1" style="width: 138px;">0</button>

Now, we have to further beautify our calculator. It involves that when the button is hovered/clicked it should change colour accordingly, giving a more realistic look.

https://kcldtzblfykiwwltfouv.supabase.co/storage/v1/object/sign/meta/1__Tau4TLzhMbvioLcVqvsVQA.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJtZXRhLzFfX1RhdTRUTHpoTWJ2aW9MY1ZxdnNWUUEucG5nIiwiaWF0IjoxNjYzNjczMTI2LCJleHAiOjE5NzkwMzMxMjZ9.8qF4VHKqQLw7GCXMnaXZd99-HwkkCwqENtc2awafXwo&t=2022-09-20T11%3A25%3A26.271Z

For this, we have to change the cursor to a pointer and the background colour a bit darker when it’s covered. Also, it should look a bit darker when it's clicked upon.

button:hover {
 cursor: pointer;
 background-color: rgb(182, 178, 178);
}

button:active {
 background-color: rgb(136, 136, 136);
}

Woohoo!! We have designed our calculator. By this time, it looks like:

https://kcldtzblfykiwwltfouv.supabase.co/storage/v1/object/sign/meta/1__gTMPtTqJANp9hQconOyLqQ.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJtZXRhLzFfX2dUTVB0VHFKQU5wOWhRY29uT3lMcVEucG5nIiwiaWF0IjoxNjYzNjczMTM4LCJleHAiOjE5NzkwMzMxMzh9.KDqrNtmZpkTvJMB3u0rbfEPsJpaBplfwxTNukip3e9E&t=2022-09-20T11%3A25%3A38.611Z

But it’s still lifeless. We have to give it life.

So let’s dive into the backend section and make the calculator solve our problems.

Let’s make a JavaScript file, say “script.js”. We have to link it to our HTML file as well.

Place the code inside the head tag.

<script src="script.js">

Now it’s linked to our HTML file.

Now let’s make our first function, that clears any mess on the output screen, which comes into play when the “C” button is triggered.

Let’s call our function forclear().

The concept behind the working of this function is that it should get the value of the output screen and set it to default (i.e. 0).

function forclear() {
      document.getElementById("output").innerHTML = "0";
}

Also, this won’t come into action unless we assign this function to the C button. For that, we go to the HTML section and add the property to the C button that onclick(), it should trigger this function.

<button id="r1-1" _onclick="forclear()"_ style="width: 138px;">
     C
</button>

Great. Now any equation on the output screen will be cleared by clicking the clear button.

Now we have to define a function that removes the default 0 on the output screen, otherwise, any value updated on the output screen will be concatenated with 0, like this:

https://kcldtzblfykiwwltfouv.supabase.co/storage/v1/object/sign/meta/1__8oXrtRbo__QPMzmXBebxO2g.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJtZXRhLzFfXzhvWHJ0UmJvX19RUE16bVhCZWJ4TzJnLnBuZyIsImlhdCI6MTY2MzY3MzE1OCwiZXhwIjoxOTc5MDMzMTU4fQ.DQvWCcCb7QxSeaxZIdsp284lGWMLVy9Cjad7A5oAeqA&t=2022-09-20T11%3A25%3A58.682Z

This does not look nice and logical. We have to remove this zero before any operation starts.

So, we define a new function “removeZero()”, that replaces the 0 with just a gap if 0 is present before any operation starts.

function removeZero() {
      var value = document.getElementById("output").innerHTML;
      if (value == "0") {
           value = " "
           document.getElementById("output").innerHTML = value;
      }

}

Next, we have to define a function to find the percentage of the value on the output screen when the “%” button is triggered.

For that, we define a function as perc(), that gets value from the output screen, divides it by 100 and then sends it back.

function perc() {
      var value = document.getElementById("output").innerHTML;
      value = value / 100;
      document.getElementById("output").innerHTML = value;
}

But remember, this will not work unless we say the % button to do so. Go to the HTML section and define the property “onclick”.

<button id="r1-3" onclick="perc()"> % </button>

Great, now % would also work.

Now 2 things are left: Updating the value on the output screen when any button is clicked and solving the equation on the output screen once the “=” button is clicked.

Let's code for displaying the values on the output screen.

For this, we define a new function fordisplay(value), where value is the parameter that is nothing but the numerical values or arithmetic operators.

Let’s see the code:

function fordisplay(value) {
      removeZero()
      document.getElementById("output").innerHTML += value;

}

It first removes the zero by removeZero() function discussed above.

Then it updates the value of the output screen with the value or operator which is triggered.

But we have to define the “onclick” property for each and every number and operator in the HTML section.

The “value” will be replaced with what is triggered.

Example:

<button id="r3-1" value="4" _onclick="fordisplay('4')_ ">4</button>

The above code is defined for the button “4”. You have to do this for the rest buttons as well.

Your code will look like this:

https://kcldtzblfykiwwltfouv.supabase.co/storage/v1/object/sign/meta/1__ZF0IlPrd7YXoSz__gWrMvQw.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJtZXRhLzFfX1pGMElsUHJkN1lYb1N6X19nV3JNdlF3LnBuZyIsImlhdCI6MTY2MzY3MjgzMiwiZXhwIjoxOTc5MDMyODMyfQ.TWNtKa5oww5kScbgvB8lLCXd6B2Iy4pswASTOouR72g

Now whatever we press on the calculator, it gets updated on the output screen.

Still, the purpose of the calculator is not served.

We have to display the output once the “=” button is triggered.

For that, we define a function solve() for that.

But the question is how we are going to solve the equation?

Thanks to JavaSript, we have a function eval(equation) that evaluates/executes the equation passed as a parameter. We’ll be using that concept here.

function solve() {
     removeZero()
     var equation = document.getElementById("output").innerHTML;
     var solved = eval(equation);
     document.getElementById('output').innerHTML = solved;
}

Obviously, our first process will be to remove the zero. Thanks for removeZero() we have discussed above. Then we will fetch the equation from the output screen using its id.

Then we have created a variable solved that stores the value of the evaluated expression.

(You might think there was no need to store the value anywhere as it’s not used anywhere else. EASTER EGG: You can make an advanced version of this calculator project, which even saves the history of the user’s calculations. )

Next, we update the output screen with the value stored in solved. That’s the answer to the equation user sent for solving.

In the final step, we have to tell the “=” button what it has to do once it's clicked.

<button id="r5-3" value="=" onclick="solve()" >=</button>

That’s it!!!

Congratulations!!!

You have made your own calculator. It’s working and looks good as well. It solves problems as well. Great!

https://kcldtzblfykiwwltfouv.supabase.co/storage/v1/object/sign/meta/1__coCXlkRyHIUbzJHUgJNelw.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJtZXRhLzFfX2NvQ1hsa1J5SElVYnpKSFVnSk5lbHcucG5nIiwiaWF0IjoxNjYzNjczMTkyLCJleHAiOjE5NzkwMzMxOTJ9.hgsOsNuQLFxs2y1FYCJ9m9ggw-XYiH_Gue8B0NFoPrY&t=2022-09-20T11%3A26%3A32.678Z

Stuck somewhere? Drop me a DM on Twitter

You can also watch me code this project in this video.

Thanks a lot for reading.

Have an amazing day ahead!!!