Welcome to the beginner-friendly tutorial on building a JavaScript Calculator! In this project, we'll create a fully functional calculator that can perform basic and advanced operations. This project is an excellent way to learn how to work with event listeners, complex logic, and DOM manipulation.
Before we begin coding, let's set up a workspace for our project. This folder will be your digital canvas, where you'll keep all the project files organized.
Create a new folder on your computer to store all your project files. You can name it "javascript-calculator".
On Windows:You'll need a text editor to write your code. We recommend Visual Studio Code, which is free and beginner-friendly.
We need three essential files for our project:
To create these files:
🎯 Success Check: You should now have:
👉 Tip: If something's not working, try restarting VS Code or creating the files using the "File → New File" menu.
Let's start by building the HTML structure for our calculator. HTML is like the foundation of our app.
<!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="container">
<h1>JavaScript Calculator</h1>
<div id="calculator">
<input type="text" id="display" disabled>
<div class="buttons">
<button class="btn" id="clear">C</button>
<button class="btn" id="delete">DEL</button>
<button class="btn" id="divide">/</button>
<button class="btn" id="multiply">*</button>
<button class="btn" id="seven">7</button>
<button class="btn" id="eight">8</button>
<button class="btn" id="nine">9</button>
<button class="btn" id="subtract">-</button>
<button class="btn" id="four">4</button>
<button class="btn" id="five">5</button>
<button class="btn" id="six">6</button>
<button class="btn" id="add">+</button>
<button class="btn" id="one">1</button>
<button class="btn" id="two">2</button>
<button class="btn" id="three">3</button>
<button class="btn" id="equals">=</button>
<button class="btn" id="zero">0</button>
<button class="btn" id="decimal">.</button>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Let's break down the HTML structure:
<div class="container">
: The main container for our app.<h1>JavaScript Calculator</h1>
: The title of our app.<div id="calculator">
: The container for the calculator.<input type="text" id="display" disabled>
: The display for showing the current input and result.<div class="buttons">
: The container for the buttons.<button class="btn" id="clear">C</button>
: The button to clear the display.<button class="btn" id="delete">DEL</button>
: The button to delete the last character.<button class="btn" id="divide">/</button>
: The button for division.<button class="btn" id="multiply">*</button>
: The button for multiplication.<button class="btn" id="seven">7</button>
: The button for the number 7.<button class="btn" id="eight">8</button>
: The button for the number 8.<button class="btn" id="nine">9</button>
: The button for the number 9.<button class="btn" id="subtract">-</button>
: The button for subtraction.<button class="btn" id="four">4</button>
: The button for the number 4.<button class="btn" id="five">5</button>
: The button for the number 5.<button class="btn" id="six">6</button>
: The button for the number 6.<button class="btn" id="add">+</button>
: The button for addition.<button class="btn" id="one">1</button>
: The button for the number 1.<button class="btn" id="two">2</button>
: The button for the number 2.<button class="btn" id="three">3</button>
: The button for the number 3.<button class="btn" id="equals">=</button>
: The button to calculate the result.<button class="btn" id="zero">0</button>
: The button for the number 0.<button class="btn" id="decimal">.</button>
: The button for the decimal point.<script src="script.js"></script>
: Includes the JavaScript file for handling the app's functionality.Save your "index.html" file. Now we have the basic HTML structure in place. In the next step, we'll add some styling to make it look nice! 🎨
CSS is like the paint and brushes we use to make our app visually appealing. Let's add some styles to our calculator.
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
box-sizing: border-box;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
h1 {
margin: 0 0 20px;
font-size: 1.5rem;
}
#calculator {
text-align: left;
}
#display {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 1.2rem;
text-align: right;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.btn {
width: 100%;
padding: 15px;
border: none;
border-radius: 5px;
font-size: 1rem;
cursor: pointer;
transition: background-color 0.3s ease;
}
.btn:hover {
background-color: #f0f0f0;
}
#clear, #delete, #equals {
background-color: #007bff;
color: #fff;
}
#clear:hover, #delete:hover, #equals:hover {
background-color: #0056b3;
}
#divide, #multiply, #subtract, #add {
background-color: #ff9800;
color: #fff;
}
#divide:hover, #multiply:hover, #subtract:hover, #add:hover {
background-color: #ff8c00;
}
#decimal, #zero, #one, #two, #three, #four, #five, #six, #seven, #eight, #nine {
background-color: #4a90e6;
color: #fff;
}
#decimal:hover, #zero:hover, #one:hover, #two:hover, #three:hover, #four:hover, #five:hover, #six:hover, #seven:hover, #eight:hover, #nine:hover {
background-color: #3a7cbb;
}
Let's understand the CSS rules we just added:
body
: Sets the default font, removes margins and padding, and centers the content on the screen..container
: Styles the container with a white background, padding, rounded corners, and a shadow.h1
: Styles the title with a larger font size and margin.#calculator
: Styles the calculator container with text alignment.#display
: Styles the display input with a fixed width, padding, border, and font size..buttons
: Uses grid layout to arrange the buttons..btn
: Styles the buttons with padding, border-radius, font size, cursor, and transition for smooth changes..btn:hover
: Changes the background color on hover.#clear, #delete, #equals
: Styles the special buttons with a blue background and white text.#clear:hover, #delete:hover, #equals:hover
: Changes the background color on hover.#divide, #multiply, #subtract, #add
: Styles the operation buttons with an orange background and white text.#divide:hover, #multiply:hover, #subtract:hover, #add:hover
: Changes the background color on hover.#decimal, #zero, #one, #two, #three, #four, #five, #six, #seven, #eight, #nine
: Styles the number buttons with a teal background and white text. and changes the background color on hover.Save your "styles.css" file. Now, if you open "index.html" in a web browser, you'll see the styled calculator. 🎉
Now, let's add JavaScript to make our calculator interactive! We'll handle button clicks and perform calculations.
First, we need to select the HTML elements we want to work with. We'll select the display input and all the buttons.
// Selecting HTML elements
const display = document.getElementById('display');
const buttons = document.querySelectorAll('.btn');
Here, we're using the getElementById
andquerySelectorAll
methods to select the display input and all the buttons.
Next, we'll create a function to handle button clicks. This function will determine what to do based on the button clicked.
// Function to handle button clicks
function handleButtonClick(event) {
const button = event.target;
const value = button.textContent;
if (button.id === 'clear') {
clearCalculator();
} else if (button.id === 'delete') {
deleteLastCharacter();
} else if (button.id === 'equals') {
calculateResult();
} else {
updateDisplay(value);
}
}
This function checks the ID of the button clicked and calls the appropriate function based on the button's ID.
Now, let's create a function to clear the calculator display.
// Function to clear the calculator
function clearCalculator() {
display.value = '';
}
This function sets the display value to an empty string, effectively clearing the display.
Next, let's create a function to delete the last character from the display.
// Function to delete the last character
function deleteLastCharacter() {
display.value = display.value.slice(0, -1);
}
This function uses the slice
method to remove the last character from the display value.
Now, let's create a function to update the display with the value of the button clicked.
// Function to update the display
function updateDisplay(value) {
if (value === 'C' || value === 'DEL' || value === '=') {
return;
}
display.value += value;
}
This function checks if the value is 'C', 'DEL', or '=' and returns early if it is. Otherwise, it appends the value to the display.
Finally, let's create a function to calculate the result of the expression in the display.
// Function to calculate the result
function calculateResult() {
const expression = display.value;
try {
const result = eval(expression);
display.value = result.toString();
} catch (error) {
display.value = 'Error';
}
}
This function uses the eval
function to evaluate the expression in the display. If the evaluation is successful, it sets the display value to the result. If an error occurs, it sets the display value to 'Error'.
Now, let's add event listeners to all the buttons so that they trigger the handleButtonClick
function when clicked.
// Adding event listeners to buttons
buttons.forEach(button => {
button.addEventListener('click', handleButtonClick);
});
This code iterates over all the buttons and adds a click event listener to each one, calling the handleButtonClick
function when a button is clicked.
Now that we have the HTML, CSS, and JavaScript in place, let's put it all together and test our calculator.
If everything is working correctly, you should be able to perform basic and advanced operations using the calculator.
Congratulations! You've completed the JavaScript Calculator project. You've learned how to create a fully functional calculator that can perform basic and advanced operations. This project introduced you to working with event listeners, complex logic, and DOM manipulation.
Feel free to customize and expand your calculator further. You can add more features, improve the design, or even create a mobile version. Happy coding and exploring the world of web development! 🚀