DEV Community

Cover image for Create a simple calculator using HTML, CSS and Javascript
Adam Nagy
Adam Nagy

Posted on • Updated on

Create a simple calculator using HTML, CSS and Javascript

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>
Enter fullscreen mode Exit fullscreen mode

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: &larr;. 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">&larr;</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>
Enter fullscreen mode Exit fullscreen mode

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">
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Apply the missing two sides of the borders for every button:

.buttons > div {
    border-top: 1px solid #999;
    border-right: 1px solid#999;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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'));
Enter fullscreen mode Exit fullscreen mode

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;
        }
    });
});
Enter fullscreen mode Exit fullscreen mode

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:

Discussion (8)

Collapse
webreflection profile image
Andrea Giammarchi

imho, no beginner should ever prefer <div class="button"></div> over <button></button> ... ever!

Collapse
bkilinc profile image
bkilinc

this isn't a form button, name could be "calcButton" etc.

Collapse
webreflection profile image
Andrea Giammarchi

This is button, with all accessibility concerns a button should have. A button exists with or without a form, and in this case it's the right tool for the job. With a form, it could work even without JS, by submitting value click after click.

Thread Thread
bkilinc profile image
bkilinc

Mostly, you are right. But a button may render differently accross browsers, needs reseting etc. May be, it is too much for a beginners article. I am not an advocate. Just exploring dev.to after a while.

Thread Thread
webreflection profile image
Andrea Giammarchi

A beginner should never ditch accessibility for layout that can be easily fixed ... layout is easy to fix, broken accessibility is a barrier.

Collapse
shine18 profile image
Aakash Ahmed

Awesome tutorial. Well written.
I've also written a tutorial in the topic but with more simplified approach easy to learn for beginners.
Create a simple calculator in javascript.

Collapse
millytexas profile image
Milly texas • Edited on

Excellent. It's really an informative stuff. I will be very useful for my post
strength quotes

Collapse
speculatrix profile image
Paul M

Hello,
I checked out the github repo and the style.css file was 0 bytes