Create a simple calculator using HTML, CSS and Javascript
Adam Nagy
Posted on October 26, 2021
In this tutorial we will create a fully working calculator using only HTML, CSS and vanilla Javascript. You'll learn about event handling, and DOM manipulations throughout the project. In my opinion this is a really good beginner project for those who want to become web developers.
Video Tutorial
If you would watch a detailed step-by-step video instead you can check out the video I made covering this project on my Youtube Channel:
HTML
The html will be pretty simple for this project. We'll start out with a standard HTML5 boilerplate. At the bottom of our body I included the index.js
script that we will create later. This needs to be at the bottom, because this way, when our javascript runs, the html elements required for the calculator will be in the DOM.
In the body we have a section
and inside that a div with a container
class. We will use these wrappers to position our calculator on the page. Inside our container we have an empty div with the id of display
, and this will be the display of our calculator. It is empty, because we will modify its content from Javascript. Then we have a div with the class of buttons
which will represent the keypad of the calculator.
<body>
<section>
<div class="container">
<div id="display"></div>
<div class="buttons">
</div>
</div>
</section>
<script src="index.js"></script>
</body>
The buttons
container will hold all of the buttons. Each button will be a div with a class of button
. This will make the styling easy, and also will help us to gather the user input. Here we have a div for every button that we want on our keypad. You can notice that we have a weird looking label between the buttons: ←
. This is a HTML entity and it renders a back arrow (←), and we'll use this as a backspace. Also please not that for the equal sign button we have a separate id equal
. We will use this Id to distinguish this special button, and evaluate the expression provided to the calculator.
<div class="buttons">
<div class="button">C</div>
<div class="button">/</div>
<div class="button">*</div>
<div class="button">←</div>
<div class="button">7</div>
<div class="button">8</div>
<div class="button">9</div>
<div class="button">-</div>
<div class="button">4</div>
<div class="button">5</div>
<div class="button">6</div>
<div class="button">+</div>
<div class="button">1</div>
<div class="button">2</div>
<div class="button">3</div>
<div class="button">.</div>
<div class="button">(</div>
<div class="button">0</div>
<div class="button">)</div>
<div id="equal" class="button">=</div>
</div>
And this is all of the HTML markup that we need for this project, let's jump into CSS.
Don't forget to link the CSS styleshead in the head of the HTML file:
<link rel="stylesheet" href="style.css">
CSS
Let's create a style.css
file.
We set a width for the container and center it using margin (also give it a decent top margin of 10vh), and apply a little box shadow.
.container {
max-width: 400px;
margin: 10vh auto 0 auto;
box-shadow: 0px 0px 43px 17px rgba(153,153,153,1);
}
For the display we set a fixed height, and to center the text vertically we need to set the line-height to the exact same amount. The text should be right align, because this is how most calculator displays work. Also set the font-size and give a decent amount paddings.
#display {
text-align: right;
height: 70px;
line-height: 70px;
padding: 16px 8px;
font-size: 25px;
}
To position the buttons we use CSS grid. By setting 4 x 1fr in-grid-template-coloumns
we'll have 4 equally sized buttons in each row. We only set bottom and left borders, so we won't get double borders. We'll set the other two sides in the next CSS rule.
.buttons {
display: grid;
border-bottom: 1px solid #999;
border-left: 1px solid#999;
grid-template-columns: 1fr 1fr 1fr 1fr;
}
Apply the missing two sides of the borders for every button:
.buttons > div {
border-top: 1px solid #999;
border-right: 1px solid#999;
}
For the button we'll set borders, font-size and 100px of line height to center it vertically, and set text-align: center
to center the button labels horizontally. To have a better user experience set cursor to pointer, so the user will know that this is a clickable element.
.button {
border: 0.5px solid #999;
line-height: 100px;
text-align: center;
font-size: 25px;
cursor: pointer;
}
We want the equal button to stand out so, we'll set a blue background color and white text to it. Also to have a nice hover effect we'll set a darker background color and white text color on hover. To make the transition smoot set: transition: 0.5s ease-in-out;
.
#equal {
background-color: rgb(85, 85, 255);
color: white;
}
.button:hover {
background-color: #323330;
color: white;
transition: 0.5s ease-in-out;
}
Javascript
This will be the heart of our application. Let's create the index.js
file. The first thing we need to do is to save a reference to our display dom element. We can easily do that because it has an id of display
.
let display = document.getElementById('display');
Next we have to get references for the buttons. We'll store the button references in an array. To gather the buttons we can select them by document.getElementsByClassName('button')
, but this function gives back a NodeCollection instead of an array so we have to convert it to an array using Array.from()
.
let buttons = Array.from(document.getElementsByClassName('button'));
The next and last step we have to make is to add event listener to the buttons and build the functionalities. To add event listeners for the buttons, we'll map through the buttons array and add a click event listener for each. (An advanced solution would be to only add event listener to the buttons
container and use event bubbling but this is a more beginner-friendly solution.)
To determine what should we do, we'll use e.target.innerText
, which will simply give back the label of the button that was clicked.
In the first case, when the user hits the "C" button we'd like to clear the display. To do that we can access our display reference and set the innerText
to an empty string. Don't forget to add break;
at the end, because it is needed to prevent the execution of the code defined in other case
blocks.
For the equal button we'll use javascript built in eval
function. We need to provide the display's content to eval and it will evaluate and return the result, so we should set the result of the eval call to the display's innerText. We need to wrap this into a try catch block to handle errors. Erros can happen when we have syntactically wrong math expressions, for example //(9(
, ine these cases we'll set the display's innerText to display 'Error'.
⚠️ You should not use eval in user facing applications, because it can be abused and external code can be run with it. More details If you want to replace eval I suggest using Math.js lib.
If the user hits the back arrow we need to remove the last character from the display's innerText. To do that we'll use the String.slice() method, but we only want to do that if the display has any value.
In the default case, so whenever the user don't hit these special symbols we just want to append the clicked button's innerText to the display's innerText. We can use the +=
operator to do that.
buttons.map( button => {
button.addEventListener('click', (e) => {
switch(e.target.innerText){
case 'C':
display.innerText = '';
break;
case '=':
try{
display.innerText = eval(display.innerText);
} catch {
display.innerText = "Error"
}
break;
case '←':
if (display.innerText){
display.innerText = display.innerText.slice(0, -1);
}
break;
default:
display.innerText += e.target.innerText;
}
});
});
The whole project is available on GitHub
And that's it you have a working calculator.
Thanks for reading.
Where you can learn more from me?
I create education content covering web-development on several platforms, feel free to 👀 check them out.
I also create a newsletter where I share the week's or 2 week's educational content that I created. No bull💩 just educational content.
🔗 Links:
- 🍺 Support free education and buy me a beer
- 💬 Join our community on Discord
- 📧 Newsletter Subscribe here
- 🎥 YouTube Javascript Academy
- 🐦 Twitter: @dev_adamnagy
- 📷 Instagram @javascriptacademy
Posted on October 26, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.