Creating a calculator app is an excellent project to practice web development skills. This blog will walk you through the process of building a functional calculator from designing the user interface (UI) to implementing the core logic. I have used HTML, CSS, and JavaScript to create the app.
Step 1: Designing the User Interface (HTML and CSS)
The first step is to create a clean and intuitive UI for our calculator. Here’s how I approached the design.
I have created a .wrapper class which is a container that centers the calculator on the screen. It ensures the calculator is both vertically and horizontally aligned, providing a clean layout.
.wrapper {
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
border: 2px solid black;
background-color: rgb(167, 219, 219);
}
Inside the wrapper container, I have put another class .calculator-container for a calculator display screen and buttons. By using display: flex; and flex-direction: column; the child elements stack vertically with a gap of 12px between them.
.calculator-container {
display: flex;
flex-direction: column;
gap: 12px;
width: 500px;
}
Each row of buttons is wrapped in a .flex-container class. This class uses display: flex; to arrange the buttons in a horizontal row. The gap: 12px; property creates consistent spacing between the buttons, ensuring they are visually appealing and user-friendly.
.flex-container {
display: flex;
flex-wrap: nowrap;
gap: 12px;
}
The .display-box class styles the calculator’s result display area. The text-align: end; property aligns the text to the right and font-size: 24px; makes the text easy to read. The rounded corners and background colour improve aesthetics.
.display-box {
padding: 24px;
border: 1px solid black;
border-radius: 8px;
text-align: end;
font-size: 24px;
background-color: aliceblue;
}
This is how the UI looks at the end. I have also given some background colour and border radius to make it visually appealing.
Step 2: Adding Functionality with Javascript
Now that we have the UI, Let's Implement the logic to make the calculator functional.
JavaScript:
1.Selecting Elements
We need to interact with the display box and all the buttons. Let’s start selecting these elements.
const displayBox = document.querySelector(".display-box");
const calculatorBtn = document.querySelectorAll("button");
2.Handling Button Clicks
We loop through all the buttons using forEach and attach a click event listener to each. The listener calls the handleButtonAction function with the button’s value as an argument. This ensures that each button's functionality is dynamically handled based on its value.
const handleButtonAction = (buttonValue) => {}
let displayValue = "";
calculatorBtn.forEach((btn) => {
const buttonValue = btn.innerText;
btn.onclick = () => {
handleButtonAction(buttonValue);
};
});
3.Updating the display
The display () function updates the display box with the current value or a default 0.0.
const display = () => {
displayBox.innerText = displayValue || "0.0";
};
4.Append Button Value
o Purpose: Adds the button’s value to the input string.
o Explanation: Handles all other valid inputs (numbers and operators) by appending them to the existing string.
displayValue += buttonValue; // Append the button value to the display
display();
5.Handling Button Actions
The if conditions in the handleButtonAction function are used to process the different types of button clicks (e.g., clearing input, appending values, handling operators) and ensure valid calculations. Let’s break them down:
- Evaluate Expression ( “=” or Enter Key)
o Purpose: Evaluate the mathematical expression in displayValue.
o Explanation:
- The eval () function computes the results of the mathematical expression.
- The results are converted to a string and stored in displayValue for display
if (buttonValue === "=" || buttonValue === "Enter") {
const result = eval(displayValue); // Calculate the result
displayValue = String(result);
display();
return;
}
2.Clear All (AC button)
o Purpose: clears the entire input.
o Explanation: This resets displayValue to an empty string, effectively clearing the display box.
if (buttonValue === "AC") {
displayValue = ""; // Clear the entire display
display();
return;
}
3.Clear Last Character (C button)
• Purpose: Deletes the last character from displayValue.
• Explanation: The slice(0, -1) method removes the last character of the string, making it useful for correcting minor input mistakes.
if (buttonValue === "C") {
displayValue = displayValue.slice(0, -1); // Remove the last character
display();
return;
}
4.Prevent Invalid Operator Use
o Purpose: Ensures operators are used in a valid context.
o Explanation:
- Prevents operators at the start of the expression(!displayValue)
- Prevents two consecutive operators (checks the last character for another operator).
if (["%", "/", "*", "+", "-"].includes(buttonValue)) {
if (!displayValue || displayValue.slice(-1).match(/[\%\*\+\-\/]/)) {
return; // Prevent invalid operators
}
}
5.Handle Decimal Point (.button)
o Purpose: Ensures a number contains only one decimal point.
o Explanation:
- Splits displayValue into chunks based on operators (e.g., 12.5+3 becomes ["12.5", "3"]).
- Checks the last chunk (number after the last operator).
- If the last number already has a decimal, it prevents appending another.
if (buttonValue === ".") {
const lastNumberSet = displayValue.split(/[\%\*\+\-\/]/).pop();
if (lastNumberSet.includes(".")) return; // Prevent multiple decimals
}
6.Onkeypress Event Listener
- Purpose: To make the calculator work with keyboard as well.
Explanation:
- we used addEventListener event to the document and it takes two parameters, "keyPress" and "event". It checks if the code includes any "Key" and returns it.
document.addEventListener("keypress", (event)=>{
console.log("event", event.key);
if(event.code.includes("Key")){
return
}
handleButtonAction(event.key)
})
Key Highlights
Valid Expressions: We ensure valid inputs by preventing consecutive operators, disallowing operators at the start, and handling decimal inputs properly.
Dynamic Updates: The display() function updates the UI in real time, giving users instant feedback.
Simplified Logic: Using eval() simplifies the calculation process, but be cautious about its use in production environments.
Final Thoughts
Building this calculator was an excellent exercise in combining HTML, CSS, and JavaScript to create a functional and interactive web application. From designing an intuitive UI to implementing robust input handling, this project covers essential concepts for aspiring web developers.
Try building your own version and experiment with adding new features or styling it differently! Let me know your thoughts or questions in the comments below.
Top comments (0)