
Building a Simple Calculator with HTML, CSS, and JavaScript

Creating a calculator application is a great way to practice your web development skills. This project involves HTML for the structure, CSS for styling, and JavaScript for functionality. In this article, I’ll walk you through the process of creating a simple calculator step by step.
Project Structure
Here’s the structure of our project:
calculator/
├── index.html
├── style.css
└── app.js
Step 1: Setting Up the HTML
The HTML file provides the basic structure of the calculator. We will use a form for the screen and buttons for the numbers and operations.
Step 2: Styling with CSS
The CSS file styles the calculator to make it visually appealing. We’ll define styles for the calculator container, buttons, and screen.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}body {
min-height: 100vh;
background: white;
display: flex;
justify-content: center;
align-items: center;
}
.calculator {
width: 300px;
height: 500px;
box-shadow: 4px 4px 30px rgba(0,0,0,0.2);
border-radius: 12px;
background: #222522;
overflow: hidden;
}
form input {
width: 100%;
height: 150px;
border: none;
border-radius: 12px;
font-size: 2rem;
padding: 1rem;
color: #fff;
background: #000;
text-align: right;
pointer-events: none;
}
.button {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
padding: 20px;
}
button {
flex: 0 0 22%;
margin: 5px 0;
border: 1px solid #000;
width: 60px;
height: 52px;
font-size: 22px;
font-weight: 600;
border-radius: 5px;
cursor: pointer;
}
.btn-yellow {
background: rgb(245, 146, 62);
color: #fff;
}
.btn-grey {
background: rgb(224, 224, 224);
color: #000;
}
.btn-equal {
background: green;
color: #fff;
}
.btn-clear {
background: red;
color: #fff;
}
Step 3: Adding Functionality with JavaScript
The JavaScript file will add functionality to our calculator, such as handling button clicks and performing calculations.
(function() {
let screen = document.querySelector('.screen');
let buttons = document.querySelectorAll('.btn');
let clear = document.querySelector('.btn-clear');
let equal = document.querySelector('.btn-equal');
- (function() { ... })();: This is an Immediately Invoked Function Expression (IIFE). It runs immediately after it's defined. It's used to create a private scope to avoid polluting the global namespace.
- let screen = document.querySelector('.screen');: Selects the HTML element with the class screen (the input field) and assigns it to the screen variable.
- let buttons = document.querySelectorAll('.btn');: Selects all HTML elements with the class btn (all the calculator buttons) and assigns them to the buttons variable as a NodeList.
- let clear = document.querySelector('.btn-clear');: Selects the HTML element with the class btn-clear (the clear button) and assigns it to the clear variable.
- let equal = document.querySelector('.btn-equal');: Selects the HTML element with the class btn-equal (the equal button) and assigns it to the equal variable.
buttons.forEach(function(button) {
button.addEventListener('click', function(e) {
let value = e.target.dataset.num;
if (value !== undefined) {
screen.value += value;
}
});
});
- buttons.forEach(function(button) { ... });: Iterates over each button in the NodeList buttons.
- button.addEventListener('click', function(e) { ... });: Adds a click event listener to each button.
- let value = e.target.dataset.num;: Retrieves the value of the data-num attribute of the clicked button and assigns it to the value variable.
- if (value !== undefined) { screen.value += value; }: If the value is defined (not undefined), it appends the value to the current value of the screen input field. This builds the arithmetic expression on the screen as the user clicks buttons.
equal.addEventListener('click', function(e) {
if (screen.value === '') {
screen.value = "Please enter";
} else {
try {
let answer = eval(screen.value);
screen.value = answer;
} catch (error) {
screen.value = "Error";
}
}
});
- equal.addEventListener('click', function(e) { ... });: Adds a click event listener to the equal button.
- if (screen.value === '') { screen.value = "Please enter"; }: Checks if the screen is empty. If it is, sets the screen value to "Please enter" as an error message.
- else { try { ... } catch (error) { ... } }: If the screen is not empty, tries to evaluate the arithmetic expression.
- let answer = eval(screen.value);: Uses the eval function to evaluate the expression in the screen input field and assigns the result to the answer variable.
- screen.value = answer;: Sets the screen value to the result of the evaluation.
- catch (error) { screen.value = "Error"; }: If there is an error during the evaluation (e.g., syntax error), sets the screen value to "Error".
clear.addEventListener('click', function(e) {
screen.value = "";
});
- clear.addEventListener('click', function(e) { ... });: Adds a click event listener to the clear button.
- screen.value = "";: Clears the screen by setting its value to an empty string.
})()
- })();: Ends the IIFE, which executes the function immediately after defining it.
Summary
- The IIFE creates a private scope to avoid global namespace pollution.
- The screen, buttons, clear, and equal variables hold references to the relevant HTML elements.
- Event listeners are added to all buttons to handle clicks:
- Number and operator buttons append their value to the screen.
- The equal button evaluates the expression and displays the result or an error message.
- The clear button resets the screen.
How It Works
- HTML: The index.html file sets up the structure of the calculator. It includes an input field for the screen and buttons for the numbers and operations.
- CSS: The style.css file styles the calculator, making it look clean and modern. It defines the layout, colors, and overall appearance.
- JavaScript: The app.js file adds interactivity. It handles button clicks, updates the screen with input values, performs calculations using the eval function, and clears the screen when needed.
Conclusion
Building a simple calculator is a great way to practice and improve your web development skills. By understanding how HTML, CSS, and JavaScript work together, you can create more complex and functional web applications in the future.
Feel free to explore and enhance this basic calculator with additional features like keyboard support, more operations, or improved error handling.
You can find the complete source code for this project on my GitHub repository. Happy coding!