Building Basic Calculator using HTML, CSS and JavaScript

Building Basic Calculator using HTML, CSS and JavaScript

Project Ideas for Front End Developers - Beginner

I like to start my blogs with low-res un-funny memes, it's now my Hello.

image.png


What's up, folks? I hope your days are going well and your code is running as well. Sending best wishes to everyone out there!

About The Project:

The motivation to build this calculator was purely from the task given as an assignment from school. As you know, even though I am currently a CS student - I put off two years without learning anything and am here now to learn on my own. You can read my whole story here.

Basic Structure for the Calculator:

  • create a table (you can use div) // Use whichever of them is more convenient for you
  • For the display box, use textarea or <input type="text">
  • For number and arithmetic signs, use buttons

image.png

The image above was the very first draft I made for executing the project.

The project does not take a lot of your time in the HTML and CSS part. And even though the Javascript linked in the project is minimal - it may take time to understand everything going on inside-out for the working! There were the silliest mistakes I made while writing the code for this and it was not fun at all - will talk about them in a few.

Building the Calculator:

I would highly recommend for you try making the project at least once with the steps I mention below before moving to the code, the only purpose here is for you to understand and learn better.

Steps:

a. Create an HTML file

b. Follow the Basic Structure:

Basic Structure for the Calculator:
  - create a table (you can use div) // Use whichever of them is more convenient for you
  - For the display box, use `textarea` or `<input type="text">`
  - For number and arithmetic signs, use buttons
  - Don't forget to give *id* to your HTML elements
  - Don't forget to add the onclick event for linking the js

c. Once you are done with the HTML part, move on to styling your calculator. In this step, you can change the padding, margin, border, and font family for the buttons and textarea used.

d. For Javascript, there are three main functions you will need:

  • Function to display the values in the display box - each button exceptC and = will have on click event which should be linked to this function.
  • Function to evaluate the arithmetic expressions in the display box - the = sign will be linked to this function which shall give us the answers for our operation.
  • Function to clear out the display box in order to continue with a new calculation - the button for C will be linked to this function

The Code:

I will be linking the GitHub repository and CodePen where the whole code has been uploaded and then I will be explaining the code in brief below!

I recommend that you try to make the Calculator on your own taking references and you can always drop a dm or tag me on social media with your questions!

Explanation of The Code:

For the HTML code: The whole calculator has been structured using a table. Each new line horizontally is made using the tr tag and for crossing it vertically and making a box, td tag has been used. Two types of input tags have been used, text and button. Onclick event has been used which calls Javascript functions.

<table border="2" align="center">
    <tr class="calrow" align="center">
      <td colspan="4">
        <input type="text" name="input" size="25" id="ip">

      </td>
    </tr>
    <tr class="calrow" align="center">
      <td>
        <input type="button" value="9" name="b9" onclick="disp('9')" class="keys">
      </td>
      <td>
        <input type="button" value="8" name="b8" onclick="disp('8')" class="keys">
      </td>
      <td>
        <input type="button" value="7" name="b7" onclick="disp('7')" class="keys">

      </td>
      <td>
        <input type="button" value="+" name="pls" onclick="disp('+')" class="keys">

      </td>
    </tr>
    <tr class="calrow" align="center">
      <td>
        <input type="button" value="6" name="b6" onclick="disp('6')" class="keys">
      </td>
      <td>
        <input type="button" value="5" name="b5" onclick="disp('5')" class="keys">
      </td>
      <td>
        <input type="button" value="4" name="b4" onclick="disp('4')" class="keys">

      </td>
      <td>
        <input type="button" value="-" name="mns" onclick="disp('-')" class="keys">

      </td>
    </tr>
    <tr class="calrow" align="center">
      <td>
        <input type="button" value="3" name="b3" onclick="disp('3')" class="keys">
      </td>
      <td>
        <input type="button" value="2" name="b2" onclick="disp('2')" class="keys">
      </td>
      <td>
        <input type="button" value="1" name="b1" onclick="disp('1')" class="keys">

      </td>
      <td>
        <input type="button" value="/" name="dv" onclick="disp('/')" class="keys">

      </td>
    </tr>
    <tr class="calrow" align="center">
      <td>
        <input type="button" value="c" name="clr" onclick="clrscr()">
      </td>
      <td>
        <input type="button" value="0" name="b0" onclick="disp('0')" class="keys">
      </td>
      <td>
        <input type="button" value="=" name="eql" onclick="ev()">

      </td>
      <td>
        <input type="button" value="*" name="mul" onclick="disp('*')" class="keys">

      </td>
    </tr>
  </table>

For the CSS part: For the table, tr and td - values for the border have been used. If you want to know more about CSS-Borders, you can visit the following link. Then for the input type text which gives a layout to the display box of the Calculator and button - the border has been removed so that the table cell's border is only visible. Further, in the background colour - it has been set to white and the 4th parameter - '0.1' gives the opacity of the colours which will make the boxes transparent. Then padding and margin have been set to give a pleasing layout.

I wanted my calculator to look a bit aesthetic and thus, I used a URL image to put in the background.

table {
  margin-top: 20px;
  background-image: url(https://p.favim.com/orig/2018/07/21/soft-pastel-soft-bambi-aesthetic-Favim.com-6074902.jpg);
  border: 2px solid black;
}

tr {
  border: 2px solid black;
}

td {
  border: 2px solid black;
}

input[type="button"] {
  width: 100%;
  background-color: rgb(255, 255, 255, 0.1);
  font-size: 24px;
  padding: 25px 64px;
  border: none;
}

input[type="text"] {
  text-align: right;
  width: 90%;
  padding: 20px 30px;
  background-color: rgb(255, 255, 255, 0.1);
  border: none;
}

For the JavaScript Code: The function display is connected to the text box or display box where the Onclick event is called for each button in the calculator except for "=" and "C". The function ev is used to evaluate the arithmetic problem in the display box. The function gets into action when someone clicks on "=". This is an inbuilt function of Javascript "eval" which helps in evaluation. The last function is used to clear the text box where the whole screen is simply replaced with a blank.

function disp(val) {
  document.getElementById("ip").value += val;
}

function ev() {
  let y = eval(document.getElementById("ip").value);

  document.getElementById("ip").value = y;
}

function clrscr() {
  document.getElementById("ip").value = "";
}

The Mistakes I Made: (That you shall avoid)

  1. I assigned two IDs to my display box element and then kept applying CSS and JS on the first one. You do realise that it would not work however much you scramble around. Took a few hours for me to realise this mistake.

  2. For Javascript, I named the function ev() as evaluate() before and didn't realize that that would be a built-in function which cannot be named for a user-defined function. I did the same for clrscr() function and named it as clr() which again gave me problems. It is important to see that while the logic was correct for each function, the naming brought problems!

Take care of these and you are good to go!

Other Integrations that can be made:

Here are some updates I wish to make in the Calculator and you can take ideas from these too!

  1. Add an event for when Enter key is pressed and that would evaluate the mathematical string in display box.
  2. Add parenthesis () for solving a little more confidential expressions.
  3. Add a BackSpace function
  4. Taking the same code base and making a scientific calculator
  5. Make the calculator more aesthetic (somehow)

Alrighty! Hello there if you survived till here! I had so much fun making this project and I hope you do too! I will be sharing and explaining more codes in future as well! You can leave a comment or connect with me directly if you have any suggestions or want to make some projects and share them with you all!

If you do not know who I am, here goes nothing! I am Krupali aka Chai (literally) and I am a third-year computer student who is now on a self-learning journey towards web-dev and many other languages. Apart from that, I am a content writer - so hit me up for your content writing needs! I contribute to OpenSource right now by suggesting changes in ReadMe files and documentation.

You can connect with me on:

Twitter || LinkedIn

Folks! Here we end it really! Hoping you have great health! Tata!

Did you find this article valuable?

Support Krupali Trivedi by becoming a sponsor. Any amount is appreciated!