# How to Create a Simple Calculator with JavaScript

In this tutorial, you'll learn the basics of creating a simple calculator with vanilla JavaScript, CSS, and HTML. My goal was to simplify and lessen the amount of code as much as possible but is proven to be extremely useful and effective. Let's get right into the code!

## The HTML

First, let's get the HTML for our calculator layout out of the way:

`<div class="calculator">	<div class="output">0</div>	<div class="btn" data-type="operator" data-id="+">+</div>	<div class="btn" data-type="operator" data-id="-">−</div>	<div class="btn" data-type="operator" data-id="*">×</div>	<div class="btn" data-type="operator" data-id="/">÷</div>	<div class="btn" data-type="number" data-id="7">7</div>	<div class="btn" data-type="number" data-id="8">8</div>	<div class="btn" data-type="number" data-id="9">9</div>	<div class="btn" data-type="equal" data-id="=" id="equal">=</div>	<div class="btn" data-type="number" data-id="4">4</div>	<div class="btn" data-type="number" data-id="5">5</div>	<div class="btn" data-type="number" data-id="6">6</div>	<div class="btn" data-type="number" data-id="1">1</div>	<div class="btn" data-type="number" data-id="2">2</div>	<div class="btn" data-type="number" data-id="3">3</div>	<div class="btn" data-type="clear" data-id="C">C</div>	<div class="btn" data-type="number" data-id="0">0</div>	<div class="btn" data-type="symbol" data-id=".">.</div></div>`

This layout displays the overall calculator container along with the numeric display and buttons, including the numbers, symbols, operations, etc.

Each of the buttons has two data attributes associated with them:

• data-id: The ID of the button, used to perform the calculations. I've included this because some of the symbols used to perform the calculations are different than their button text counterparts on computers versus how we're used to seeing them in the real world. For example, `×` is `*`, `÷` is `/`, etc.
• data-type: The type of the button, used to determine what action should be taken to update the display of the equation. This could include a numeric value, operator, etc.

## The CSS

The next part of our JavaScript calculator is the CSS code to style the calculator container and buttons:

`body {	background-color: #15171d;	padding: 0px;	margin: 0px;	overflow: hidden;}div.calculator {	width: 100%;	font-family: "Arial", sans-serif;	max-width: 500px;	padding: 3%;	margin: 40px auto;	display: block;}div.output {	width: 94%;	background-color: #ddd;	font-size: 32px;	color: #333;	text-align: right;	padding: 5% 1.5%;	margin: 1.5%;	float: left;}div.btn {	width: 22%;	background-color: #555;	font-size: 20px;	color: white;	text-align: center;	padding: 5% 0px;	margin: 1.5%;	float: left;	cursor: pointer;	transition: 0.25s all ease-in-out;	-moz-transition: 0.25s all ease-in-out;	-webkit-transition: 0.25s all ease-in-out;}div.btn[data-type="operator"]div.btn[data-type="symbol"] {	background-color: #333;}div.btn[data-type="equal"] {	background-color: #ce3078;	padding: 31.25% 0px;	float: right;}div.btn:hover {	opacity: 0.75;}@media (max-width: 768px) {	div.btn[data-type="equal"] {		padding: 33.5% 0px;	}}`

I'm not going to go into this too much because the primary focus is the JavaScript portion. So, to briefly explain this, we're stretching the output container across the entirety of the calculator while each of the buttons is one-fourth the width of the calculator itself and styled out in a grid format using `float` rules.

Each of the buttons has a transition speed of 250 milliseconds so hovering over each of the buttons with a mouse enacts an animation. It just adds a cool effect and makes the calculator feel more user-friendly overall.

Now that we've gone through the potatoes of the calculator, let's get into the meat!

## The JavaScript

The true power of this calculator comes with the JavaScript code. First, let's create a set of variables that we'll use in entirety of the example:

`var output = document.getElementsByClassName("output")[0];var equation = "";var number = "";var id = "";var type = "";`

Here is a breakdown of each of the variables:

• `output`: This variable is the display of our JavaScript calculator that shows the most current input or output depending on the button sequence clicked. It's a pointer to the HTML element with class name `output` so we don't have to continually point to it again later on.
• `equation`: This variable stores all of the user input, which we will evaluate each time an operator button is clicked or the equal `=` button is clicked.
• `number`: This variable stores the digits and decimals input by the user and is used for display purposes only. When you select a set of digits or a decimal, it will display until an operator is selected or the equal `=` button is clicked, then it resets again as more digits are selected. Doing so keeps the display cleaned up and easy to read.
• `id`: This variable stores the ID attribute of the button clicked.
• `type`: This variable stores the type attribute of the button clicked.

Next, we'll create event handlers for each of the JavaScript calculator buttons. When a button is clicked, the `id` and `type` variables are assigned using the button attribute values so we can determine how to format our equation.

`var buttons = document.getElementsByClassName("btn");for (var i = 0; i < buttons.length; i++) {	buttons[i].addEventListener("click", function() {		id = this.getAttribute("data-id");		type = this.getAttribute("data-type");		switch (type) {			case "clear":				Clear();				break;			case "operator":				Operator();				break;			case "symbol":				Symbol();				break;			case "equal":				Equal();				break;			default:				Default();				break;		}	}, false);}`

Each of the type attributes determines which action will be performed, or which function call will be made.

## The `Clear()` Method

The `Clear()` method clears the latest user input and the equation, and resets the output display to 0:

`function Clear() {	number = "";	equation = "";	output.innerHTML = 0;}`

## The `Operator()` Method

The `Operator()` method appends the selected operator to the end of the equation and updates the calculator's display. The `number` variable is also reset to keep the calculator display clean like previously explained:

`function Operator() {	equation += id;	output.innerHTML = number + " " + id;	number = "";}`

## The `Symbol()` Method

The `Symbol()` method is only used to append a decimal point to the user-input number:

`function Symbol() {	number += id;	equation += id;	output.innerHTML = number;}`

## The `Equal()` Method

The `Equal()` method evaluates the entire equation up to this point and displays the answer to the screen. The user can continue to add more to the equation by selecting additional operators and numbers:

`function Equal() {	number = eval(equation);	equation = number;	output.innerHTML = number;}`

## The `Default()` Method

The `Default()` method handles all numeric button click events by the user and updates the equation and display accordingly:

`function Default() {	number += id;	equation += id;	output.innerHTML = number;}`

## Keyboard Input

The last piece of this JavaScript calculator example is an event handler to handle user input with a keyboard. When I use a calculator on a computer, I generally use the keyboard to type out the equation versus clicking each button individually, so I thought it would be useful to include in this tutorial:

`document.addEventListener("keyup", function(event) {	if (event.keyCode != 13) {		for (var i = 0; i < buttons.length; i++) {			var id = buttons[i].getAttribute("data-id");			if (id == event.key) {				buttons[i].click();			}		}	}	else {		document.getElementById("equal").click();	}}, false);`

A `keyup` event handler is added to the `document` object, with a `for` loop that matches the user input from the keyboard to any of the existing buttons on the calculator. If one of the buttons exists, then it triggers a button click event on the selected button. If the Enter button is pressed on the keyboard, then the equal `=` button on the calculator is clicked, solving the equation.

## Conclusion

This JavaScript calculator tutorial is pretty basic but packs a punch with the amount of functionality offered and such a little amount of code.

You can download, clone, or fork the full code example from the GitHub repository and update or use it to your liking. Enjoy!

Posted by: Josh Rowe
Last Updated: January 09, 2022
Created: December 17, 2021