Want to know how to build a JavaScript calculator? In this tutorial, I’ll walk you through this fun and practical JavaScript project step-by-step.
Whether you’re just starting your web development journey or are keen to learn JavaScript, a JavaScript calculator is a fun project for beginners to learn real-world JavaScript skills.
In this JavaScript tutorial, you’ll:
- Design a user-friendly interface for a JavaScript calculator app.
- Implement core functionalities with JavaScript, such as performing arithmetic operations and managing user inputs.
- Dynamically update the calculator display to reflect calculations in real-time.
- Enhance usability with additional features like clearing entries, deleting the last digit, and handling decimal inputs.
To make the most of this tutorial, it helps to have basic web development skills, including familiarity with HTML and CSS.
Some previous experience with JavaScript, such as manipulating HTML DOM elements and handling events, can also be helpful. However, you don't need to be a JavaScript pro or have prior experience with JavaScript calculator apps.
I’ve also provided the full source code for this JavaScript project so you can follow along, experiment, and even build upon it for your own projects.
Plus, you can follow along with me using our online JavaScript compiler, so you don't need an IDE to code this JavaScript project from scratch.
JavaScript Editor for This Project
Use this JavaScript project editor to build and test code right here.
How To Build A JavaScript Calculator Web App
Are you ready to dive into JavaScript web development with a classic JavaScript project?
You're in the right place because today, we're going to build a JavaScript calculator web app using HTML, CSS, and JavaScript.
This project is perfect for JavaScript beginners or newcomers to web development, as it’s a creative way to learn how these three fundamental web technologies come together to create interactive web applications.
At the core of our project, JavaScript will play a pivotal role. It's the engine under the hood that brings our calculator to life, handling user input, performing calculations, and displaying the results.
I like to think that JavaScript acts as the brain, adding functionality and interactivity to the structural foundation provided by HTML and the stylistic enhancements of CSS.
But functionality isn't where we stop. We'll also focus on making our calculator visually appealing and user-friendly, utilizing our CSS skills to design an interface that's not only functional but also elegant and easy to use.
Take a look at the image I’ve included below to see what you’re going to be building!
Wondering about the difficulty? Worry not!
I’ve designed this JavaScript project to be beginner-friendly, with straightforward and easy-to-follow steps.
Whether you're just starting in web development or have some HTML and CSS experience but are new to JavaScript, this project will bolster your skills and confidence.
So, let's gear up, switch on our favorite web development IDE, and get ready to create our very own JavaScript calculator app.
By the end of this tutorial, you'll have not only a functional calculator to add to your portfolio but also a deeper understanding of how JavaScript, HTML, and CSS collaborate to create dynamic and interactive web applications.
Let's get started and create something practical and impressive!
Project Prerequisites
Before we delve into creating our JavaScript calculator app, let's review the skills needed to follow along.
And remember, you don't have to be a JavaScript expert to start this project, but having a grasp of the basics will make the process smoother and more enjoyable.
Plus, if you're rusty in any of these areas, you can always brush up with a JavaScript course.
Remember, we’re also here to help, so don’t hesitate to search hackr.io for help as you go along.
A Touch of HTML
HTML is the scaffold of any web application, similar to a building's framework. You should be comfortable with basic HTML elements like <div>, <button>, and the general structure of an HTML document.
If you've ever created a simple webpage or played around with HTML at school or on a web development course, you're good to go!
Basic CSS Skills
CSS is the paintbrush we use to style our web pages, adding aesthetics and polish to our HTML structure.
For this Calculator app, a basic understanding of CSS, including styling elements with colors, fonts, and layout properties, is essential. If you've experimented with making web pages visually appealing, you're ready for this project.
JavaScript Fundamentals
JavaScript brings our calculator to life, enabling it to respond to user inputs and perform calculations. Familiarity with variables, functions, basic data types, and event handling is all you’ll need.
If you're comfortable with these concepts, you're well-prepared to embark on this project. A quick review of a JavaScript cheat sheet might also be helpful for a refresher.
A Curious and Experimental Mind
The most critical requirement is your willingness to learn by doing, embracing mistakes, and problem-solving.
Be prepared to experiment with your code, debug issues, and learn from the challenges you encounter. This exploratory approach is key to growth and learning in programming.
You could also consider using an AI coding assistant like GitHub Copilot to help out, but I’d recommend waiting until you’re 100% stuck, as this is where you really learn.
Step 1: Setting Up The Project
Alright! Let's get started by setting up our project. This step is all about laying the groundwork for our JavaScript calculator web app.
If you want to dive straight in, I'd recommend following along with me using our online JavaScript compiler. This is pre-populated with the HTML, CSS, and JavaScript files you need to build this JavaScript project without switching on an IDE.
Alternatively, I've outlined the steps for you to create the necessary files and organize your workspace on your own computer. Just follow these, and you'll have a solid foundation for your project.
i. Create a Project Folder
First things first, let's keep things tidy. Create a new folder on your computer where you'll store all the files for this project. You can name it something like calculator-app.
ii. Initialize Your Files
Inside your project folder, you're going to create three essential files:
- index.html: This will be the main HTML file for your project.
- style.css: This CSS file will hold all your styling rules to make your calculator look great.
- script.js: Here's where the magic happens – your JavaScript code goes in this file.
You can create these files using a code editor like VSCode and Sublime Text, or even a text editor like Notepad. Just make sure to save them with the correct extensions.
iii. Link Your CSS and JavaScript Files
Once you've created these files, you need to link them together. Open your index.html file and add the following lines of code inside the <head> tag for the CSS:
<link rel="stylesheet" href="style.css">
And right before the closing </body> tag, add this line for the JavaScript:
<script src="script.js"></script>
These lines tell your HTML file where to find the CSS and JavaScript files and incorporate them into your webpage.
iv. Open Your Project in a Browser
Now, let's see what we've got. Open your index.html file in a web browser.
You won't see much yet – a blank page – but that's about to change. If the page opens without any errors, you're all set!
v. Ready Your Tools
As you work through the next steps, keep your code editor and web browser open side by side. This will allow you to make changes to your code and immediately see the results in the browser.
And there you have it! You've successfully set up your project, and you're ready to dive into the exciting part.
Let's move on to Step 2, where we'll start crafting the HTML structure.
Step 2: Crafting The Calculator Interface With HTML
With our Calculator project ready to go, it's time to dive into the HTML structure.
In this step, we'll craft the necessary HTML to create a sleek and user-friendly calculator interface. Let's get into the details.
i. Start with Basic HTML Structure
Open your index.html file, and let's start by laying down the foundational structure of an HTML document. Here's a quick refresher for those who might need it:
<!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="style.css">
</head>
<body>
<!-- Calculator will be constructed here -->
<script src="script.js"></script>
</body>
</html>
This setup includes the DOCTYPE declaration, HTML tag, head section (with meta tags, title, and CSS link), and the body for our content.
ii. Adding the Calculator Components
Within the <body> tag, we'll start building our calculator's components. Here’s how you might structure it:
<div id="calculator">
<div id="display">
<div id="previous-operand"></div>
<div id="current-operand"></div>
</div>
<button type="button" class="span-two" id="clear">AC</button>
<button type="button" class="span-two" id="delete">DEL</button>
<button type="button" class="number" id="number-7">7</button>
<button type="button" class="number" id="number-8">8</button>
<button type="button" class="number" id="number-9">9</button>
<button type="button" class="operation" id="divide">/</button>
<button type="button" class="number" id="number-4">4</button>
<button type="button" class="number" id="number-5">5</button>
<button type="button" class="number" id="number-6">6</button>
<button type="button" class="operation" id="multiply">*</button>
<button type="button" class="number" id="number-3">3</button>
<button type="button" class="number" id="number-2">2</button>
<button type="button" class="number" id="number-1">1</button>
<button type="button" class="operation" id="subtract">-</button>
<button type="button" class="number" id="number-0">0</button>
<button type="button" class="dot" id="dot">.</button>
<button type="button" id="equals">=</button>
<button type="button" class="operation" id="add">+</button>
</div>
In this layout:
- We have a main container div with the ID calculator.
- Inside, a div with the ID display holds the operands for our calculations.
- Individual button elements represent the calculator's buttons, including numbers, operations (like add, subtract, multiply, divide), and functionalities like clear (AC) and delete (DEL).
iii. Checking Your Work
After implementing these changes, save and refresh your web page.
You may not see much styling yet, but the basic calculator structure (buttons and display area) should be visible. This confirms that your HTML structure is set up correctly.
iv. Understanding the HTML Structure
The <div>, <button>, and other elements work together to create a structured and interactive interface for the calculator. Each element plays a crucial role in the app's functionality and user experience.
v. Tips on HTML Best Practices
While focusing on building the calculator's functionality, ensure your HTML is clean and well-organized.
This practice is vital for maintainability and scalability. Consider commenting your HTML to clarify the purpose of different sections, especially beneficial for larger projects or teamwork.
Congratulations! You've successfully set up the basic HTML structure for your Calculator app.
This foundation is straightforward but essential for adding the dynamic and interactive elements in the next steps.
Well done reaching this milestone—let's keep up the momentum as we move into Step 3, where we'll bring our calculator to life with CSS!
Step 3: Styling the Calculator With CSS
With our Calculator's HTML structure ready, it's time to turn our attention to CSS to enhance the visual appeal and usability of our app.
This step will transform our basic layout into an elegant and user-friendly calculator interface. Let's infuse some design flair into our Calculator!
i. Begin with Basic Styles
Open your style.css file. We'll start by applying some foundational styles to ensure our Calculator looks great on any device:
body {
font-family: 'Arial', sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(to right, #3a1c71, #d76d77, #ffaf7b);
color: #333;
}
#calculator {
width: auto;
max-width: 400px;
padding: 20px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
Here, we're:
- Setting a universal font for a clean and consistent look.
- Using Flexbox to center the Calculator vertically and horizontally on the page.
- Applying a full viewport height for the body for a full-screen effect.
- Adding a colorful gradient background for a dynamic and modern appearance.
- Defining the style for our main Calculator container with padding, border-radius, and a box-shadow for a sleek look.
ii. Style the Display and Buttons
Next, let's style the calculator display and buttons for a clear and intuitive user interface:
#display {
box-sizing: border-box;
width: calc(100% - 35px);
margin-bottom: 20px;
margin-left: 5px;
padding: 10px;
background-color: #ebebeb;
border-radius: 5px;
text-align: right;
font-size: 2em;
}
button {
width: 20%;
padding: 15px 0;
margin: 5px;
border: none;
border-radius: 5px;
background-color: #f0f0f0;
font-size: 1.2em;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #d4d4d4;
}
button.operation {
background-color: #fe9241;
color: #fff;
}
button.operation:hover {
background-color: #ffab62;
}
button.span-two {
width: calc(40% + 15px);
}
In this section, we're:
- Styling the display area with a background color, padding, and rounded corners.
- Designing the calculator buttons with consistent sizing, spacing, and interactive hover effects.
- Distinguishing operation buttons with a different background color to make them stand out.
iii. Save and Refresh
After applying these styles, save your style.css file and refresh your browser. Your Calculator should now display a defined, attractive, and interactive interface.
iv. Experiment with Styles
Feel free to customize the styles further. Experiment with different colors, fonts, and layouts to match your personal preference or branding.
And that's it! You've successfully styled your JavaScript Calculator, making it not only functional but also visually appealing and user-friendly.
Great work on completing this step. Next, we'll move on to the exciting part of our web development project – adding adding functionality with JavaScript.
Step 4: JavaScript - Implementing Basic Operations
Now that our Calculator app has a polished look, it's time to infuse it with functionality using JavaScript.
In this step, we'll lay the groundwork for our app's core features, focusing on variable initialization and event listener setup. Let's dive into the code!
i. Start with Basic JavaScript Setup
Open your script.js file. We'll start by identifying and storing references to key elements of our calculator interface:
const calculator = document.getElementById('calculator');
const displayCurrent = document.getElementById('current-operand');
const displayPrevious = document.getElementById('previous-operand');
const numberButtons = document.querySelectorAll('.number');
const operationButtons = document.querySelectorAll('.operation');
const equalsButton = document.getElementById('equals');
const clearButton = document.getElementById('clear');
const deleteButton = document.getElementById('delete');
const dotButton = document.getElementById('dot');
Here, we're:
- Selecting the main calculator container and display elements by their IDs.
- Gathering collections of number and operation buttons using their class names for group handling.
- Identifying special function buttons (equals, clear, delete, dot) directly by their IDs.
ii. Adding Event Listeners for Button Clicks
Next, we need to ensure our calculator responds to user interactions. We'll start by adding event listeners to the number and operation buttons:
numberButtons.forEach(button => {
button.addEventListener('click', () => {
appendNumber(button.innerText);
updateDisplay();
});
});
operationButtons.forEach(button => {
button.addEventListener('click', () => {
chooseOperation(button.innerText);
updateDisplay();
});
});
In these snippets, appendNumber and chooseOperation are placeholder functions we'll define to handle number entry and operation selection, respectively.
We’ll also use updateDisplay to refresh the calculator's display.
iii. Handling Special Functions
We'll also set up listeners for our clear, delete, and equals buttons, as well as handling decimal points:
clearButton.addEventListener('click', clear);
deleteButton.addEventListener('click', deleteNumber);
equalsButton.addEventListener('click', compute);
dotButton.addEventListener('click', appendDot);
function clear() {
// Function to clear the calculator's state
}
function deleteNumber() {
// Function to delete the last entered number or decimal
}
function compute() {
// Function to compute the expression
}
function appendDot() {
// Function to handle decimal point input
}
These functions will need to be defined to perform their respective actions, which include clearing the display, deleting the last input, calculating the result, and adding a decimal point.
iv. Testing Your Setup
After implementing these foundational features, save your script.js file and refresh your browser.
At this stage, your functions might not yet perform calculations or update the display, but you should ensure that each button click is recognized and linked to the correct handler.
In the next steps, we'll flesh out the functionality for operations, calculations, and display updates. Keep up the excellent work!
Step 5: JavaScript - Enhancing Functionality
Let’s now enhance the functionality of our Calculator app by implementing the core features that allow it to perform calculations.
We'll focus on handling number inputs, operations, and the computation logic. Let's dive into the details.
i. Handling Number Inputs
We need a way to handle number button clicks and append the clicked number to the current display. Here's how we can implement an appendNumber function we mentioned in step 4:
let currentOperand = '';
let previousOperand = '';
let operation = null;
function appendNumber(number) {
if (number === '.' && currentOperand.includes('.')) return; // Prevent multiple decimals
currentOperand = currentOperand.toString() + number.toString();
}
In this function, we're concatenating the clicked number to the currentOperand. We also check to ensure that we don't add more than one decimal point.
ii. Choosing an Operation
When a user clicks an operation button, we need to set the chosen operation and move the current operand to the previous operand if necessary. Here's the chooseOperation function:
function chooseOperation(selectedOperation) {
if (currentOperand === '') return;
if (previousOperand !== '') {
compute();
}
operation = selectedOperation;
previousOperand = currentOperand;
currentOperand = '';
}
This function sets the operation, moves the currentOperand to previousOperand, and clears the currentOperand for the next input. It also calls compute if there's already an operation pending, allowing for chained operations.
iii. Computing the Result
The compute function performs the calculation based on the chosen operation and operands:
function compute() {
let computation;
const prev = parseFloat(previousOperand);
const current = parseFloat(currentOperand);
if (isNaN(prev) || isNaN(current)) return;
switch (operation) {
case '+':
computation = prev + current;
break;
case '-':
computation = prev - current;
break;
case '*':
computation = prev * current;
break;
case '/':
computation = prev / current;
break;
default:
return;
}
currentOperand = computation;
operation = undefined;
previousOperand = '';
updateDisplay(); // Refresh the display with the new state
}
This function converts the operands to numbers, performs the calculation based on the operation, and updates currentOperand with the result.
iv. Updating the Display
To reflect changes in the display, we need to update the updateDisplay function mentioned in Step 4:
function updateDisplay() {
document.getElementById('current-operand').innerText = currentOperand;
document.getElementById('previous-operand').innerText = previousOperand + ' ' + (operation || '');
}
This function updates the calculator's display with the current and previous operands, and shows the chosen operation next to the previous operand.
v. Testing Calculator Functionality
With these features implemented, save your script.js file and refresh your browser to test the calculator.
Try performing basic calculations to ensure numbers are appended correctly, operations update as expected, and results are computed and displayed accurately.
In the next steps, we'll further refine the app, adding more sophisticated features and polishing the user experience. Keep up the fantastic work!
Step 6: JavaScript - Improving User Experience
We'll now focus on enhancing the user experience of our Calculator app by implementing additional functionalities such as clearing the display, deleting the last digit, and handling decimal inputs.
i. Clearing the Calculator
The clear function resets the calculator to its initial state. Implementing this function allows users to start a new calculation without refreshing the page:
function clear() {
currentOperand = '';
previousOperand = '';
operation = null;
updateDisplay();
}
When the clear button (AC) is clicked, it triggers this function to reset currentOperand, previousOperand, and operation, then updates the display.
ii. Deleting the Last Digit
The deleteNumber function removes the last digit from the current operand, providing users with a way to correct mistakes:
function deleteNumber() {
currentOperand = currentOperand.toString().slice(0, -1);
updateDisplay();
}
This function converts currentOperand to a string (if it isn't already), slices off the last character, and updates the display.
iii. Handling Decimal Inputs
The appendDot function ensures that only one decimal point can be added to the current operand. This function is crucial for inputting decimal numbers:
function appendDot() {
if (currentOperand.includes('.')) return; // Prevent multiple decimals
if (currentOperand === '') currentOperand = '0'; // If empty, start with '0.'
currentOperand += '.';
updateDisplay();
}
This function checks if currentOperand already contains a decimal point and, if not, appends one. If currentOperand is empty, it prepends '0' before the decimal.
iv. Event Listeners for New Functionalities
Ensure that your clear, deleteNumber, and appendDot functions are connected to their respective buttons through event listeners.
These should have been set up in previous steps, but here's a reminder:
clearButton.addEventListener('click', clear);
deleteButton.addEventListener('click', deleteNumber);
dotButton.addEventListener('click', appendDot);
v. Testing Enhanced Features
With these new features implemented, save your script.js file and test the calculator in your browser.
Check the functionality of the clear (AC) button, the delete (DEL) button, and the decimal point (.) button to ensure they behave as expected.
In the next steps, you can consider adding more advanced mathematical operations, keyboard support, or even a history feature to track past calculations.
Step 7: Extending Features [Optional]
Let’s now explore how we can extend the features of our JavaScript Calculator app to include more advanced functionalities.
This optional step allows you to further enhance the app based on your interests and the needs of your users. Let's consider a few possibilities.
i. Advanced Mathematical Operations
Introduce more complex operations such as exponentiation, square roots, or percentage calculations.
For each new operation, you'll need to add a corresponding button to your HTML and extend the chooseOperation and compute functions to handle the new operations:
<button type="button" class="operation" id="square-root">√</button>
<button type="button" class="operation" id="power">^</button>
<button type="button" class="operation" id="percentage">%</button>
In your compute function, add cases for these new operations:
switch (operation) {
// Existing cases
case '√':
computation = Math.sqrt(current);
break;
case '^':
computation = Math.pow(prev, current);
break;
case '%':
computation = (prev / 100) * current;
break;
// Continue with the rest
}
ii. Keyboard Support
Enhance usability by allowing users to input numbers and operations using their keyboard.
We can do this by adding an event listener to listen out for certain keypress events, and we'll then map these keys to calculator buttons:
document.addEventListener('keydown', (event) => {
if (event.key >= 0 && event.key <= 9) appendNumber(event.key);
if (event.key === '.') appendDot();
if (event.key === 'Enter' || event.key === '=') compute();
if (event.key === 'Backspace') deleteNumber();
if (event.key === 'Escape') clear();
// Map other keys to operations
updateDisplay();
});
iii. Memory Functions
Consider adding memory functions like M+, M-, MR (Memory Recall), and MC (Memory Clear) to store and recall values:
let memoryValue = 0;
function memoryAdd() {
memoryValue += parseFloat(currentOperand);
}
function memorySubtract() {
memoryValue -= parseFloat(currentOperand);
}
function memoryRecall() {
currentOperand = memoryValue.toString();
updateDisplay();
}
function memoryClear() {
memoryValue = 0;
}
Add buttons for these memory functions in your HTML and connect them with event listeners in your JavaScript.
iv. Error Handling
Implement error handling for undefined operations or calculations that result in errors like division by zero. Update the display to show an error message in such cases.
v. Testing Extended Features
After implementing any of these advanced features, thoroughly test each one to ensure they work correctly and enhance the overall functionality of your calculator.
These enhancements not only make your app more versatile and powerful but also provide a richer experience for users.
Whether you've added complex operations, keyboard support, memory functions, or improved error handling, your calculator is now a more comprehensive tool.
I’d also encourage you to continue exploring additional features and functionalities to further expand your JavaScript project.
Step 8: Final Touches And Testing
Fantastic work on developing your JavaScript Calculator!
Now it's time to apply the finishing touches and rigorously test the application to ensure its functionality is flawless and the user experience is intuitive and engaging.
i. Review and Clean Up Code:
- Carefully examine your JavaScript, HTML, and CSS files. Seek opportunities to refine or streamline your code to enhance readability and efficiency.
- Maintain a consistent coding style, including proper indentation, use of quotes, and adherence to naming conventions, to improve code maintainability.
- Eliminate any debugging remnants like console logs, commented-out code snippets, or unnecessary comments.
ii. Cross-Browser Testing:
- Conduct tests on various browsers to verify consistent performance and visual integrity of your calculator.
- Address any compatibility issues, such as discrepancies in event listener behavior or CSS property support.
- Utilize tools like BrowserStack or Can I Use for comprehensive testing and compatibility checks.
iii. Responsive Design Testing:
- Test your calculator on different devices or use browser tools to simulate various screen sizes, ensuring the UI is responsive and functional across devices.
- Pay extra attention to how touch interactions work on mobile devices, confirming that taps are accurately registering as button presses.
iv. User Experience Enhancements:
- Enhance interaction feedback, possibly by integrating subtle animations or transition effects for button presses to create a more dynamic interface.
- Ensure the calculator is accessible, considering aspects like keyboard navigation and clear visual cues for interactions.
v. Performance Optimization:
- If your calculator includes any media or external resources, ensure they are optimized for swift loading without compromising on quality.
- Review your resource usage and script executions to guarantee efficient loading and operation, contributing to an enhanced user experience.
vi. Gather Feedback:
- If feasible, have others test your calculator. Fresh perspectives might reveal overlooked issues or offer valuable insights into UX and design aspects.
- Utilize this feedback to implement any necessary refinements to the app.
vii. Documentation and Sharing:
- Consider drafting a README file if you plan to showcase your project on platforms like GitHub, detailing the project setup and any noteworthy features.
- Share your project within developer communities or on social media to engage with a broader audience and gather additional feedback.
viii. Reflect and Plan Next Steps:
- Reflect on the knowledge gained through this project and contemplate how these learnings can be applied to future endeavors.
- Consider expanding your calculator with more complex features, like scientific calculation capabilities, a history log of calculations, or customizable themes.
Great job on building and refining your calculator web app! Take a moment to appreciate your hard work!
Whether you're building this for fun, as a learning experience, or as a portfolio piece, you've developed valuable skills in programming, problem-solving, and user interface design.
Be proud of your work, share it with others, and consider what project you'll take on next!
Next Steps & Further Learning
Congratulations on successfully building your own interactive JavaScript calculator web app!
This is a significant achievement, but your learning journey doesn't stop here. There are many ways to further your skills in web development. Let's explore some ideas:
Learn More About JavaScript and Web Technologies
- JavaScript Enhancements: Explore more advanced JavaScript concepts and apply them to your app. Could advanced calculator features like the option to add a custom math function or expression to a programmable button be added?
- Explore Frameworks: Experiment with JS frameworks like React or Vue.js to see how they can be used to build more dynamic and complex web applications.
- Web Animations: Learn about CSS animations and JavaScript to add engaging animations to your calculator.
Join Online Communities and Collaborate
- Engage in Forums: Participate in web development forums and communities. Share your calculator, get feedback, and learn from others.
- Contribute to Open Source: Consider making your calculator app open-source and collaborate with others to improve it.
Keep Up with Trends and Best Practices
Stay updated with the latest trends in web development and JavaScript. Subscribe to blogs like hackr.io, watch webinars, and join online courses.
Document and Share Your Learning Journey
- Blog About Your Project: Write about your development process, challenges you faced, and how you overcame them. Share your blog with the developer community.
- Share Your Code: Publish your code on platforms like GitHub. This not only showcases your work but also allows others to learn from your project.
Challenge Yourself Regularly
Take part in coding challenges or hackathons to sharpen your skills and learn new techniques.
And if you're hungry for more JavaScript projects, check out the rest of our step-by-step tutorials, including:
JavaScript Calculator App Full Source Code
HTML Source Code:
<!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="style.css">
</head>
<body>
<div id="calculator">
<div id="display">
<div id="previous-operand"></div>
<div id="current-operand"></div>
</div>
<button type="button" class="span-two" id="clear">AC</button>
<button type="button" class="span-two" id="delete">DEL</button>
<button type="button" class="number" id="number-7">7</button>
<button type="button" class="number" id="number-8">8</button>
<button type="button" class="number" id="number-9">9</button>
<button type="button" class="operation" id="divide">/</button>
<button type="button" class="number" id="number-4">4</button>
<button type="button" class="number" id="number-5">5</button>
<button type="button" class="number" id="number-6">6</button>
<button type="button" class="operation" id="multiply">*</button>
<button type="button" class="number" id="number-3">3</button>
<button type="button" class="number" id="number-2">2</button>
<button type="button" class="number" id="number-1">1</button>
<button type="button" class="operation" id="subtract">-</button>
<button type="button" class="number" id="number-0">0</button>
<button type="button" class="dot" id="dot">.</button>
<button type="button" id="equals">=</button>
<button type="button" class="operation" id="add">+</button>
</div>
<script src="script.js"></script>
</body>
</html>
CSS Source Code:
body {
font-family: 'Arial', sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(to right, #3a1c71, #d76d77, #ffaf7b);
color: #333;
}
#calculator {
width: auto;
max-width: 400px;
padding: 20px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
#display {
box-sizing: border-box;
width: calc(100% - 35px);
margin-bottom: 20px;
margin-left: 5px;
padding: 10px;
background-color: #ebebeb;
border-radius: 5px;
text-align: right;
font-size: 2em;
}
button {
width: 20%;
padding: 15px 0;
margin: 5px;
border: none;
border-radius: 5px;
background-color: #f0f0f0;
font-size: 1.2em;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #d4d4d4;
}
button.operation {
background-color: #fe9241;
color: #fff;
}
button.operation:hover {
background-color: #ffab62;
}
button.span-two {
width: calc(40% + 15px);
}
JavaScript Source Code:
const calculator = document.getElementById('calculator');
const displayCurrent = document.getElementById('current-operand');
const displayPrevious = document.getElementById('previous-operand');
const numberButtons = document.querySelectorAll('.number');
const operationButtons = document.querySelectorAll('.operation');
const equalsButton = document.getElementById('equals');
const clearButton = document.getElementById('clear');
const deleteButton = document.getElementById('delete');
const dotButton = document.getElementById('dot');
numberButtons.forEach(button => {
button.addEventListener('click', () => {
appendNumber(button.innerText);
updateDisplay();
});
});
operationButtons.forEach(button => {
button.addEventListener('click', () => {
chooseOperation(button.innerText);
updateDisplay();
});
});
clearButton.addEventListener('click', clear);
deleteButton.addEventListener('click', deleteNumber);
equalsButton.addEventListener('click', compute);
dotButton.addEventListener('click', appendDot);
let currentOperand = '';
let previousOperand = '';
let operation = null;
function clear() {
currentOperand = '';
previousOperand = '';
operation = null;
updateDisplay();
}
function deleteNumber() {
currentOperand = currentOperand.toString().slice(0, -1);
updateDisplay();
}
function compute() {
let computation;
const prev = parseFloat(previousOperand);
const current = parseFloat(currentOperand);
if (isNaN(prev) || isNaN(current)) return;
switch (operation) {
case '+':
computation = prev + current;
break;
case '-':
computation = prev - current;
break;
case '*':
computation = prev * current;
break;
case '/':
computation = prev / current;
break;
default:
return;
}
currentOperand = computation;
operation = undefined;
previousOperand = '';
updateDisplay(); // Refresh the display with the new state
}
function appendDot() {
if (currentOperand.includes('.')) return; // Prevent multiple decimals
if (currentOperand === '') currentOperand = '0'; // If empty, start with '0.'
currentOperand += '.';
updateDisplay();
}
function appendNumber(number) {
if (number === '.' && currentOperand.includes('.')) return; // Prevent multiple decimals
currentOperand = currentOperand.toString() + number.toString();
}
function chooseOperation(selectedOperation) {
if (currentOperand === '') return;
if (previousOperand !== '') {
compute();
}
operation = selectedOperation;
previousOperand = currentOperand;
currentOperand = '';
}
function updateDisplay() {
document.getElementById('current-operand').innerText = currentOperand;
document.getElementById('previous-operand').innerText = previousOperand + ' ' + (operation || '');
}
Wrapping Up
Building a JavaScript calculator app using HTML, CSS, and JavaScript is a fantastic way to enhance your web development skills and delve into creating interactive web applications.
By creating this practical and interactive app, you've tackled various challenges, including crafting a user-friendly interface, implementing calculation logic, and dynamically updating the webpage based on user inputs.
In this tutorial, you’ve learned how to:
- Use HTML and CSS to design a sleek and intuitive Calculator app.
- Write JavaScript to handle arithmetic operations and user inputs.
- Dynamically update HTML content with JavaScript to reflect the ongoing calculations.
- Respond to user actions by adding event listeners for number entry, operations, and utility functions like clear and delete.
You now possess the essential skills and insights to further expand and refine this JavaScript Calculator.
You might consider adding advanced features, such as scientific calculation modes, memory functions, or creating a history log of calculations, or even integrating the Calculator into a larger web application.
Your journey into the world of JavaScript doesn't end here. With these new skills, you're well-equipped to experiment with more complex JavaScript projects, explore other aspects of JavaScript, and continue building fun and interactive web experiences.
And remember, you can do all this using our online JavaScript compiler, so get creative, have fun, and happy coding!
Want to sharpen up your JavaScript and web development skills? Check out:
Dr. Angela Yu's Complete Web Development Bootcamp