Free Web Design Code & Scripts

Simple Calculator in HTML and JavaScript

Simple Calculator in HTML and JavaScript
Code Snippet:Simple Calculator
Author: José Carneiro
Published: 5 months ago
Last Updated: August 28, 2025
Downloads: 344
License: MIT
Edit Code online: View on CodePen
Read More

This tutorial will guide you through creating a simple calculator using HTML, CSS, and JavaScript. We’ll build a functional calculator that allows users to perform basic arithmetic operations.

Step 1: Setting up the Project

Include Header Assets

First, add these assets to your HTML document’s head section. This will include a Google Font for styling.

<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Open+Sans:300'>

Step 2: Creating the HTML Structure

Next, create the basic HTML structure for your calculator. This will include the display area, buttons for numbers, and operators.

<div id="calculator">
	<!-- Screen and clear key -->
	<div class="top">
		<span class="clear" data-value="C">C</span>
		<div class="input"></div>
    <div class="result"></div>
	</div>
	
	<div class="keys">
		<!-- operators and other keys -->
		<span data-value="7">7</span>
		<span data-value="8">8</span>
		<span data-value="9">9</span>
		<span class="operator" data-value="/">/</span>
		<span data-value="4">4</span>
		<span data-value="5">5</span>
		<span data-value="6">6</span>
		<span class="operator" data-value="*">x</span>
		<span data-value="1">1</span>
		<span data-value="2">2</span>
		<span data-value="3">3</span>
		<span class="operator" data-value="-">-</span>
		<span data-value="0">0</span>
		<span data-value=".">.</span>
		<span class="equals" data-value="=">=</span>
		<span class="operator" data-value="+">+</span>
	</div>
</div>

<!-- PrefixFree -->
<script src="http://thecodeplayer.com/uploads/js/prefixfree-1.0.7.js" type="text/javascript" type="text/javascript"></script>

Step 3: Styling with CSS

Now, let’s add some CSS to style our calculator and make it visually appealing. This will involve styling the layout, colors, and button appearance.

* {
  box-sizing: border-box;
  font-family: 'Open Sans', Helvetica, Arial, sans-serif;
  font-size: 24px;
  font-size: 4vw;
  font-weight: 300;
  margin: 0;
  padding: 0;
}
html {
  height: 100%;
  background: radial-gradient(circle, #fff, #ddd);
  background-size: cover;
}
#calculator {
  width: 12em;
  height: auto;
  background: linear-gradient(#4389A2, #5C258D);
  margin: 1em auto;
}
.top span.clear {
  float: left;
  box-shadow: 0 4px #ff7c87;
  color: #FFF;
}
.top .input {
  height: 3em;
  width: 9em;
  padding-right: 1em;
  float: right;
  color: #FFF;
  line-height: 3em;
  text-align: right;
  letter-spacing: 1px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
}
.keys,
.top {
  overflow: hidden;
}
.keys span,
.top span.clear {
  float: left;
  cursor: pointer;
  width: 3em;
  height: 3em;
  line-height: 3em;
  color: #fff;
  text-align: center;
  user-select: none;
  transition: background-color 0.2s ease;
  border-right: 1px solid rgba(255, 255, 255, 0.3);
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
}
.keys span.operator {
  background: rgba(255, 255, 255, 0.2);
  border-right: 0;
  color: rgba(0, 0, 0, 0.5);
}
.keys span.equals {
  color: #888e5f;
}
.keys span:hover {
  background: rgba(255, 255, 255, 0.3);
  color: #FFF;
}
.keys span.equals:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
}
.top span.clear:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #FFF;
}

Step 4: Adding JavaScript Functionality

Finally, we’ll add JavaScript code to handle user input, perform calculations, and update the display. This will involve event listeners and logic for arithmetic operations.

// Get all the keys from document
var keys = document.querySelectorAll('#calculator span');
var operators = ['+', '-', 'x', '÷'];
var decimalAdded = false;

// Add onclick event to all the keys and perform operations
for(var i = 0; i < keys.length; i++) {
	keys[i].onclick = function(e) {
		// Get the input and button values
		var input = document.querySelector('.input');
		var inputVal = input.innerHTML;
		var btnVal = this.getAttribute("data-value");
		
		// Now, just append the key values (btnValue) to the input string and finally use javascript's eval function to get the result
		// If clear key is pressed, erase everything
		if(btnVal == 'C') {
			input.innerHTML = '';
			decimalAdded = false;
		}
		
		// If eval key is pressed, calculate and display the result
		else if(btnVal == '=') {
			var equation = inputVal;
			var lastChar = equation[equation.length - 1];
			
			// Replace all instances of x and ÷ with * and / respectively. This can be done easily using regex and the 'g' tag which will replace all instances of the matched character/substring
			equation = equation.replace(/x/g, '*').replace(/÷/g, '/');
			
			// Final thing left to do is checking the last character of the equation. If it's an operator or a decimal, remove it
			if(operators.indexOf(lastChar) > -1 || lastChar == '.')
				equation = equation.replace(/.$/, '');
			
			if(equation)
				input.innerHTML = eval(equation);
				
			decimalAdded = false;
		}
		
		// Basic functionality of the calculator is complete. But there are some problems like 
		// 1. No two operators should be added consecutively.
		// 2. The equation shouldn't start from an operator except minus
		// 3. not more than 1 decimal should be there in a number
		
		// We'll fix these issues using some simple checks
		
		// indexOf works only in IE9+
		else if(operators.indexOf(btnVal) > -1) {
			// Operator is clicked
			// Get the last character from the equation
			var lastChar = inputVal[inputVal.length - 1];
			
			// Only add operator if input is not empty and there is no operator at the last
			if(inputVal != '' && operators.indexOf(lastChar) == -1) 
				input.innerHTML += btnVal;
			
			// Allow minus if the string is empty
			else if(inputVal == '' && btnVal == '-') 
				input.innerHTML += btnVal;
			
			// Replace the last operator (if exists) with the newly pressed operator
			if(operators.indexOf(lastChar) > -1 && inputVal.length > 1) {
				// Here, '.' matches any character while $ denotes the end of string, so anything (will be an operator in this case) at the end of string will get replaced by new operator
				input.innerHTML = inputVal.replace(/.$/, btnVal);
			}
			
			decimalAdded =false;
		}
		
		// Now only the decimal problem is left. We can solve it easily using a flag 'decimalAdded' which we'll set once the decimal is added and prevent more decimals to be added once it's set. It will be reset when an operator, eval or clear key is pressed.
		else if(btnVal == '.') {
			if(!decimalAdded) {
				input.innerHTML += btnVal;
				decimalAdded = true;
			}
		}
		
		// if any other key is pressed, just append it
		else {
			input.innerHTML += btnVal;
		}
		
		// prevent page jumps
		e.preventDefault();
	} 
}

Congratulations! You’ve successfully built a simple calculator using HTML, CSS, and JavaScript.

Loading... ...

Loading preview...

Device: Desktop
Dimensions: 1200x800
Lines: 0 Characters: 0 Ln 1, Ch 1

Leave a Comment

About W3Frontend

W3Frontend provides free, open-source web design code and scripts to help developers and designers build faster. Every snippet is reviewed before publishing for quality. Learn more.