Introduction
Building a simple web-based calculator is an excellent way to get started with programming for the web. This project lets you design a user-friendly tool capable of doing fundamental mathematical operations like multiplication, division, addition, and subtraction. You'll learn how to create an interactive application that responds to user interaction by combining HTML for structure, CSS for style, and JavaScript for functionality. Not only is it an excellent introductory exercise, but it also sets the framework for future more sophisticated projects.
Let's get started building your own calculator.
HTML Code
<body>
<!-- Main container for the calculator -->
<div class="calculator">
<!-- Display input field where calculations are shown; it is disabled to prevent user input -->
<input type="text" id="display" disabled />
<!-- Container for calculator buttons -->
<div class="buttons">
<!-- Number buttons: when clicked, they append their value to the display -->
<button onclick="appendValue('7')">7</button>
<button onclick="appendValue('8')">8</button>
<button onclick="appendValue('9')">9</button>
<button onclick="appendValue('+')">+</button>
<button onclick="appendValue('4')">4</button>
<button onclick="appendValue('5')">5</button>
<button onclick="appendValue('6')">6</button>
<button onclick="appendValue('-')">-</button>
<button onclick="appendValue('1')">1</button>
<button onclick="appendValue('2')">2</button>
<button onclick="appendValue('3')">3</button>
<button onclick="appendValue('*')">*</button>
<button onclick="appendValue('0')">0</button>
<button onclick="appendValue('.')">.</button>
<!-- Equals button: when clicked, it triggers the calculation of the expression in the display -->
<button onclick="calculate()">=</button>
<button onclick="appendValue('/')">/</button>
<!-- Clear button: clears the display when clicked -->
<button onclick="clearDisplay()">C</button>
<!-- Delete button: removes the last character from the display -->
<button onclick="deleteLast()">
<!-- SVG icon representing the delete action -->
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-90deg-left" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M1.146 4.854a.5.5 0 0 1 0-.708l4-4a.5.5 0 1 1 .708.708L2.707 4H12.5A2.5 2.5 0 0 1 15 6.5v8a.5.5 0 0 1-1 0v-8A1.5 1.5 0 0 0 12.5 5H2.707l3.147 3.146a.5.5 0 1 1-.708.708z" />
</svg>
</button>
</div>
</div>
</body>
This HTML code creates a simple calculator interface with buttons for numbers and operations.
CSS Code
/* Styles for the body of the page */
body {
display: flex; /* Use flexbox layout for alignment */
justify-content: center; /* Center items horizontally */
align-items: center; /* Center items vertically */
height: 100vh; /* Full height of the viewport */
background-color: hsl(218, 13%, 88%); /* Light blue background color */
font-family: Arial, sans-serif; /* Font style for the text */
margin: 0; /* Remove default margin */
}
/* Styles for the main calculator container */
.calculator {
width: 250px; /* Set fixed width for the calculator */
background-color: #ffffff; /* White background for the calculator */
border-radius: 8px; /* Rounded corners */
box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); /* Subtle shadow for depth */
overflow: hidden; /* Hide overflow content */
}
/* Styles for the display area of the calculator */
#display {
width: 90%; /* 90% of the calculator width */
height: 60px; /* Fixed height for the display */
font-size: 24px; /* Larger text size for readability */
text-align: right; /* Right-align text in the display */
padding: 10px; /* Padding inside the display */
border: none; /* Remove border */
background-color: #f8f8f8; /* Light gray background for the display */
color: #333; /* Dark text color */
}
/* Styles for the buttons container */
.buttons {
display: grid; /* Use grid layout for buttons */
grid-template-columns: repeat(4, 1fr); /* Four equal columns */
gap: 5px; /* Space between buttons */
padding: 10px; /* Padding around the button grid */
}
/* Styles for individual buttons */
button {
width: 100%; /* Full width of the grid cell */
height: 50px; /* Fixed height for buttons */
font-size: 18px; /* Text size for buttons */
border: none; /* Remove border */
background-color: #e0e0e0; /* Light gray background for buttons */
color: #333; /* Dark text color */
cursor: pointer; /* Pointer cursor on hover */
border-radius: 5px; /* Rounded corners for buttons */
}
/* Hover effect for buttons */
button:hover {
background-color: #c0c0c0; /* Darker gray on hover */
}
/* Active state for buttons when clicked */
button:active {
background-color: #a0a0a0; /* Even darker gray when active */
}
/* Special styling for every fourth button (e.g., operation buttons) */
button:nth-child(4n) {
background-color: #4caf50; /* Green background for every fourth button */
color: white; /* White text for contrast */
}
/* Special styling for the second-to-last button (clear button) */
button:nth-last-child(2) {
background-color: #f44336; /* Red background for the clear button */
color: white; /* White text for contrast */
}
This CSS style is a simple calculator with a flexbox layout, grid buttons, and a responsive design.
JavaScript Code
/**
* Appends a value to the calculator display.
*
* @param {string} value - The value to be appended (e.g., a number or operator).
*/
function appendValue(value) {
// Get the display element by its ID and append the value to its current content.
document.getElementById("display").value += value;
}
/**
* Clears the calculator display.
*/
function clearDisplay() {
// Set the value of the display to an empty string, effectively clearing it.
document.getElementById("display").value = '';
}
/**
* Deletes the last character from the calculator display.
*/
function deleteLast() {
// Get the display element by its ID.
const display = document.getElementById("display");
// Remove the last character from the display value using slice.
display.value = display.value.slice(0, -1);
}
/**
* Evaluates the expression in the calculator display and updates the display with the result.
*/
function calculate() {
try {
// Evaluate the expression in the display using eval and store the result.
const result = eval(document.getElementById("display").value);
// Update the display with the result of the evaluation.
document.getElementById("display").value = result;
} catch (error) {
// Alert the user if the evaluation throws an error (e.g., invalid operation).
alert("Invalid operation");
}
}
This JavaScript handles calculator functions like appending values, clearing the display, deleting characters, and evaluating expressions.
Output
The output shows the result of the evaluated expression.
Conclusion
Building a simple web-based calculator is the perfect gateway to mastering web development. It combines HTML, CSS, and JavaScript to create an interactive tool that responds to user input and performs real-time calculations. By completing this project, you'll unlock the skills needed for more advanced applications, learning how to seamlessly blend design, functionality, and user experience. This calculator not only serves a practical purpose but also lays a strong foundation for your future coding journey.