JavaScript Calculator Project for Beginners
Creating a JavaScript calculator project can be a fun and educational experience. In this guide, we'll walk you through building a basic calculator that can perform addition, subtraction, multiplication, and division operations. Let's get started!
Step 1: Set up the HTML
Create an HTML file (e.g., index.html
) and set up the basic structure:
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calculator">
<input type="text" class="display" disabled>
<div class="keys">
<!-- Numeric and operator keys -->
<button class="key">7</button>
<button class="key">8</button>
<button class="key">9</button>
<button class="key">+</button>
<button class="key">4</button>
<button class="key">5</button>
<button class="key">6</button>
<button class="key">-</button>
<button class="key">1</button>
<button class="key">2</button>
<button class="key">3</button>
<button class="key">*</button>
<button class="key">0</button>
<button class="key">.</button>
<button class="key" id="equals">=</button>
<button class="key">/</button>
<!-- Clear and delete buttons -->
<button class="key" id="clear">C</button>
<button class="key" id="delete">DEL</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Step 2: Style the Calculator (Optional)
Create a CSS file (e.g., styles.css
) and add some basic styling:
cssbody {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.calculator {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
max-width: 300px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.display {
grid-column: span 4;
height: 40px;
font-size: 24px;
text-align: right;
border: 1px solid #ccc;
border-radius: 5px;
padding: 5px;
}
.keys {
grid-column: span 4;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 5px;
}
.key {
height: 40px;
font-size: 18px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f9f9f9;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
}
#equals {
grid-column: span 2;
background-color: #4caf50;
color: #fff;
}
Step 3: Implement the JavaScript Calculator
Create a JavaScript file (e.g., script.js
) and write the logic for the calculator:
jsconst display = document.querySelector('.display');
const keys = document.querySelectorAll('.key');
let currentInput = '';
let previousInput = '';
let operator = null;
// Helper function to update the display
function updateDisplay() {
display.value = currentInput;
}
// Helper function to perform the calculation
function calculate() {
switch (operator) {
case '+':
currentInput = (parseFloat(previousInput) + parseFloat(currentInput)).toString();
break;
case '-':
currentInput = (parseFloat(previousInput) - parseFloat(currentInput)).toString();
break;
case '*':
currentInput = (parseFloat(previousInput) * parseFloat(currentInput)).toString();
break;
case '/':
currentInput = (parseFloat(previousInput) / parseFloat(currentInput)).toString();
break;
}
}
// Add click event listeners to the numeric and operator keys
keys.forEach((key) => {
key.addEventListener('click', () => {
const keyValue = key.textContent;
// Handle numeric input
if (!isNaN(keyValue) || keyValue === '.') {
currentInput += keyValue;
updateDisplay();
}
// Handle operator input
if (['+', '-', '*', '/'].includes(keyValue)) {
if (operator) {
calculate();
updateDisplay();
}
operator = keyValue;
previousInput = currentInput;
currentInput = '';
}
// Handle equals (=) key
if (keyValue === '=') {
if (operator) {
calculate();
operator = null;
previousInput = '';
updateDisplay();
}
}
// Handle clear (C) key
if (keyValue === 'C') {
currentInput = '';
operator = null;
previousInput = '';
updateDisplay();
}
// Handle delete (DEL) key
if (keyValue === 'DEL') {
currentInput = currentInput.slice(0, -1);
updateDisplay();
}
});
});
Step 4: Test the Calculator
Now, open the index.html
file in your web browser. You should see a basic calculator with numeric keys, operator keys, a display area, and a few extra keys for clearing and deleting input.
Test the calculator by clicking the keys and performing simple calculations. The display should show the current input, and pressing the "=" key should display the result of the calculation.
Congratulations! You've built a simple JavaScript calculator. This project can be extended in many ways, such as adding more complex operations, adding keyboard support, or enhancing the user interface. Feel free to experiment and improve upon it further!