Howdy Folks, Welcome to this new tutorial :) In this tutorial, you will learn how to build a Simple Calculator using HTML, CSS, and our favorite Javascript.

Before jumping right in first, take a look at the finished product here at Codepen --> https://codepen.io/thecodingpie/pen/VweyXmo

You can download the completed project from GitHub --> https://github.com/the-coding-pie/Calculator

Prerequisites

I assume that you had a decent understanding of HTML, CSS, and Javascript. If you already don't know them, don't worry. I will try my best to break this tutorial into simple steps and explain everything as I can.

I am going to use visual studio code as my text editor. You are free to use whatever code editor you like. And finally, make sure you have installed Live Server by Ritwick Dey in visual studio code. If you don't have Live Server installed, then:

  • Open visual studio code
  • Goto Extensions tab (Ctrl + Shift + X)
  • Search for "Live Server" by Ritwick Dey
  • Then Install it

But wait, How we are going to build this thing?

Breaking Down the logic

The logic is quite simple. We had a display to show the numbers and some keys to give input.

calculator layout breakdown

  • If the user clicks on numbers (from 0 to 9) or operators (+, -, /, *), then we should concatenate them with whatever is currently displayed inside the display screen.
  • If the user clicks on the C button (for clear), then we should clear everything on the display screen.
  • If the user clicks on the = button, then we should do the calculation and display the answer to the display screen.

That's what we all want to do and trust me it's quite simple :)

For keeping this tutorial short and simple, I am going to use the easy way. Now let's get started...

Initial Setups

This is my folder structure:

project folder structure

  • First, create the root folder which holds everything and name it as "Calculator"
  • Then open this folder in visual studio code.
  • Then directly inside the root folder, create a file named "index.html" --> This holds our HTML.
  • Then again directly inside our root folder, create two folders:
    • One named "css" --> Inside this folder, create a file named "styles.css".
    • Then another folder named "js" --> Inside this folder, create a file named "script.js".

That's it. Now you should have a folder structure similar to above. From here on I will be doing everything bit by bit so that you can get a better understanding of what we are doing... Now the HTML part...

HTML

Open the "index.html" file and type the following:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="css/styles.css">
  <title>Calculator</title>
</head>
<body>
  
  <script type="text/javascript" src="js/script.js"></script>
</body>
</html>

That's our boilerplate code. There's nothing special in there. We are giving some <meta> tags, one for setting the charset, and one for the viewport. They are not required here. But always using them is a good practice. Then we are linking our "styles.css" file. Then set the title. Before the ending </body> tag, we are linking our "script.js" file. That's it.

Now type the following code between <body> and opening <script> tag.

 <!-- calculator -->
  <div class="calculator">

    <!-- display -->
    <input type="text" class="display" disabled>
    <!-- keys -->
    <div class="keys">
      
    </div>

  </div>
  <!-- calculator body ends -->
  • The first <div> with a class="calculator" is the calculators body.
  • Inside that, we had an <input> element with type="text" and class="display". This is our display screen. But we made it disabled so that users cannot enter the digits directly inside the <input> box. You can test the difference by removing the disabled property and again adding it.
  • Then we had a <div> with class="keys". This is the div that is going to hold our keys.

Now type the following inside <div class="keys"></div>:

<!-- 4 rows of keys -->
      <div class="row">
        <button value="7">7</button>
        <button value="8">8</button>
        <button value="9">9</button>
        <button value="+" class="operator">+</button>
      </div>
      <div class="row">
        <button value="4">4</button>
        <button value="5">5</button>
        <button value="6">6</button>
        <button value="-" class="operator">-</button>
      </div>
      <div class="row">
        <button value="1">1</button>
        <button value="2">2</button>
        <button value="3">3</button>
        <button value="*" class="operator">*</button>
      </div>
      <div class="row">
        <button value="C" class="operator">C</button>
        <button value="0">0</button>
        <button value="/" class="operator">/</button>
        <button value="=" class="operator">=</button>
      </div>

Here we had 4 <div> with class="row". Each row holds four <button>. So in total 16 buttons.

We are making from the top to bottom. So in the top row, we had buttons like 7, 8, 9, and +.

And in the second row, we had buttons like 4, 5, 6, and -. So on and so forth.

Between each <button></button>, we had given the corresponding numbers and symbols.

number between button tags

And we also gave the corresponding numbers and symbols as value attribute inside the opening <button> tag so that we can get each button's value from within javascript later.

value attribute

Finally, we had added class="operator" for buttons like +, -, *, C, /, and = so that we can apply some different styles to them later.

The final code for "index.html" looks like below. Make sure the HTML code you typed up to this point is exactly like the below:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="css/styles.css">
  <title>Calculator</title>
</head>
<body>

  <!-- calculator -->
  <div class="calculator">

    <!-- display -->
    <input type="text" class="display" disabled>
    <!-- keys -->
    <div class="keys">
      <!-- 4 rows of keys -->
      <div class="row">
        <button value="7">7</button>
        <button value="8">8</button>
        <button value="9">9</button>
        <button value="+" class="operator">+</button>
      </div>
      <div class="row">
        <button value="4">4</button>
        <button value="5">5</button>
        <button value="6">6</button>
        <button value="-" class="operator">-</button>
      </div>
      <div class="row">
        <button value="1">1</button>
        <button value="2">2</button>
        <button value="3">3</button>
        <button value="*" class="operator">*</button>
      </div>
      <div class="row">
        <button value="C" class="operator">C</button>
        <button value="0">0</button>
        <button value="/" class="operator">/</button>
        <button value="=" class="operator">=</button>
      </div>
    </div>

  </div>
  <!-- calculator body ends -->
  
  <script type="text/javascript" src="js/script.js"></script>
</body>
</html>

Open it with Live Server by right-clicking on the "index.html" file (inside visual studio code), then scroll down and click on the "Open with Live Server" option and take a look at it at the browser. You can't see any styling now. Because we only linked the "styles.css" file but didn't write any CSS styles. So now let's do that. Let's add some styles...

CSS

Open the "styles.css" file you created and type the following:

/* common styles */
* {
  padding: 0;
  margin: 0;
}

body {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #222831;
  font-family: sans-serif;
}

/* common styles end */

They are some common styles. 

  • First, we are selecting everything using * and set padding: 0 and margin: 0. It will remove the default padding and margin set by the browser.
  • Then we are selecting the body element and setting:
    • width: 100vw and height: 100vh --> This will make the body to take the entire width and height.
    • overflow: hidden will hide the scrollbar if it is visible
    • display: flex, justify-content: center and align-items: center makes everything inside the body center.
    • background-color: #222831 will give a light black background color.
    • font-family: sans-serif sets the font to sans-serif.

Now below the above code, type the following:

/* calculator */
.calculator {
  width: 300px;
  padding-bottom: 15px;
  border-radius: 7px;
  background-color: #000;
  box-shadow: 5px 8px 8px -2px rgba(0, 0, 0, 0.61);
}
/* calculator style end */

This styles our calculator <div>.

  • It sets width: 300px and will give a padding-bottom: 15px and makes the border round by border-radius: 7px.
  • background-color: #000 will give a black background and box-shadow will give a shadow of x-offset 5px, y-offset 8px, blur of 8px, spread-radius of -2px and color of black with opacity 0.61.

Now again type the following code below the previous code:

/* display */
.display {
  width: 100%;
  height: 80px;
  border: none;
  box-sizing: border-box;
  padding: 10px;
  font-size: 2rem;
  background-color: #00ff44;
  color: #000;
  text-align: right;
  border-top-left-radius: 7px;
  border-top-right-radius: 7px;
}

/* display style end */

This styles our input box with the class=display. This is pretty self-explanatory. So take it as a challenge and try to decode it on your own ;)

Again type the following code below that:

/* row */
.row {
  display: flex;
  justify-content: space-between;
}
/* row style end */

/* button */
button {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: none;
  outline: none;
  font-size: 1.5rem;
  background-color: #222;
  color: #fff;
  margin: 10px;
}

button:hover {
  cursor: pointer;
}

/* button style end */

/* operator */
.operator {
  background-color: #00ff44;
  color: #000;
}

/* operator style end */

Here is the explanation:

  • The first style is for every .row. Those styles will make each button to lay horizontal and gives space-between them.
  • The second style is for every button. Again try to interpret it on your own.
  • The third style makes the cursor icon to pointer (the hand symbol) when we hover over each button.
  • The last style makes those green buttons that you saw on the finished version.

That's it our CSS part is complete.

The final code for "styles.css" is below. Make sure the code you typed up to this point inside "styles.css" is exactly like the following:

/* common styles */
* {
  padding: 0;
  margin: 0;
}

body {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #222831;
  font-family: sans-serif;
}

/* common styles end */

/* calculator */
.calculator {
  width: 300px;
  padding-bottom: 15px;
  border-radius: 7px;
  background-color: #000;
  box-shadow: 5px 8px 8px -2px rgba(0, 0, 0, 0.61);
}
/* calculator style end */

/* display */
.display {
  width: 100%;
  height: 80px;
  border: none;
  box-sizing: border-box;
  padding: 10px;
  font-size: 2rem;
  background-color: #00ff44;
  color: #000;
  text-align: right;
  border-top-left-radius: 7px;
  border-top-right-radius: 7px;
}

/* display style end */

/* row */
.row {
  display: flex;
  justify-content: space-between;
}
/* row style end */

/* button */
button {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: none;
  outline: none;
  font-size: 1.5rem;
  background-color: #222;
  color: #fff;
  margin: 10px;
}

button:hover {
  cursor: pointer;
}

/* button style end */

/* operator */
.operator {
  background-color: #00ff44;
  color: #000;
}

/* operator style end */

Javascript

How we are going to make our calculator working. Let's break them down too:

  • First, we are going to grab the reference for all the button. Then we need to grab the reference for the display box.
  • Then attach an event listener to all buttons so that all buttons will listen for a 'click' event. If any button detected the 'click' event (ie, if the user clicked on any button), then we need to activate a function called "calculate".
  • The calculate function is going to do all the magic. It will take the event object as its first argument and does the rest.

OK now just code what we have said. If you didn't understand what we have talked about, no problem just follow along, you will definitely get it.

Open the "script.js" file and type the following:

// select all the buttons
const buttons = document.querySelectorAll('button');
// select the <input type="text" class="display" disabled> element
const display = document.querySelector('.display');
  • The first line grabs every button and stores it in an array named buttons.
  • The second line grabs the input box .display and stores it in a constant called display.

Below that type the following:

// add eventListener to each button
buttons.forEach(function(button) {
  button.addEventListener('click', calculate);
});

forEach loop will loop through each <button> element inside buttons array and for each element, it activates the inner function.

The inner function takes each button and attaches a 'click' event listener. If it detects any 'click' event, then it calls the calculate function.

Now type the calculate function below that:

// calculate function
function calculate(event) {
  // current clicked buttons value
  const clickedButtonValue = event.target.value;

  if (clickedButtonValue === '=') {
    // check if the display is not empty then only do the calculation
    if (display.value !== '') {
      // calculate and show the answer to display
      display.value = eval(display.value);
    }
  } else if (clickedButtonValue === 'C') {
    // clear everything on display
    display.value = '';
  } else {
    // otherwise concatenate it to the display
    display.value += clickedButtonValue;
  }
}

The calculate function automatically gets the event object as its first argument. The event object is simple. If we print it to the console on the browser using console.log :

console log

then we can see the event object:

event object

It is just a javascript object which holds all the information about where the event happened. In our case, the event was 'click'.

  • Inside the function, we first need to get the clicked button's value. We can get it from event.target.value. Then store it inside clickedButtonValue constant.
  • Now we need to do the following check:
    • If clickedButtonValue is equal to '=' sign, then we need to make sure that there is something on the screen. ie, the screen is not empty.
      • If the screen is not empty, then take whatever expression is on the screen and do the math and again display it on the screen. We can get and set the value of the screen using display.value. And we did the math using eval() operator. It's a nice little shortcut. you can read more about eval() on here --> Eval operator
    • Else if our clickedButtonValue is equal to 'C' sign, then set the display.value empty.
    • Else, if it is not '=' sign and not 'C' sign, then it must be numbers or other operators. In that case, we need to just add them to the display. We can concatenate the value like display.value += clickedButtonValue.

Here we used the eval() operator to do the math. But using eval in real-world applications is far more dangerous. We used it here for keeping the tutorial short.

That's it here is the final code for "script.js" file:

// select all the buttons
const buttons = document.querySelectorAll('button');
// select the <input type="text" class="display" disabled> element
const display = document.querySelector('.display');

// add eventListener to each button
buttons.forEach(function(button) {
  button.addEventListener('click', calculate);
});

// calculate function
function calculate(event) {
  // current clicked buttons value
  const clickedButtonValue = event.target.value;

  if (clickedButtonValue === '=') {
    // check if the display is not empty then only do the calculation
    if (display.value !== '') {
      // calculate and show the answer to display
      display.value = eval(display.value);
    }
  } else if (clickedButtonValue === 'C') {
    // clear everything on display
    display.value = '';
  } else {
    // otherwise concatenate it to the display
    display.value += clickedButtonValue;
  }
}

Conclusion

Hooray, we did it :) Now you can play with it. If you are ready to do more, then:

  • try to add some more buttons like backspace which clears the last character.
  • or add some more operators like the remainder operator (%). Just play with it...

I hope you enjoyed this tutorial. If you had any doubts, then please comment them below. And if you enjoyed this tutorial, then please hit the like button below. Thank you ;)