Build Your Own JavaScript Calculator: A Comprehensive Step-by-Step Guide for Beginners
Hey everyone! I’m excited to share with you my journey in creating a web-based calculator app from scratch. As someone who’s passionate about the early stages of programming, I embarked on this project to hone my skills and deepen my understanding of JavaScript, HTML, and CSS.
In this blog post, I’ll walk you through the entire process of building a calculator app using HTML, CSS, and JavaScript. We’ll cover everything from the initial planning phase to the final product, discussing some of the challenges I encountered along the way and the solutions I found.
So whether you’re new to programming or just curious about how to create your own web app, this post is for you! Let’s dive in.
Project Setup
Before we dive into building our calculator web application, we need to set up our project. In this section, I’ll guide you through the process of setting up the project and running the calculator.
First, ensure you have the following installed on your machine:
- A web browser (e.g., Google Chrome, Firefox, Safari)
- A code editor (e.g., Visual Studio Code, Atom, Sublime Text)
To create the project, we’ll start by creating a new directory for the project and generating the necessary files. We’ll use HTML, CSS, and JavaScript to build our calculator.
Here are the steps to create the project:
- Open a code editor (I prefer Visual Studio Code) and create a new directory for the project.
- Create a new HTML file and name it “index.html” (this is essential if you want to use GitHub Pages).
- Create a new CSS file and name it “style.css” (or any other name as long as it has the .css extension).
- Create a new JavaScript file and name it “script.js” (or any other name as long as it has the .js extension).
Now that we have our project set up and files created, we can start building the calculator. To run the calculator in your web browser, follow these steps:
- Open your “index.html” in your web browser.
- You should see the calculator web application running in the browser!
That’s it for the project setup. We’re now ready to start building the calculator!
HTML Code
The HTML code of the calculator app lays the foundation for the user interface. It creates the structure and elements of the app, including the screen and buttons. Below is a breakdown of the HTML code used in this project:
The main container of the calculator is created using a <div> element with the class “container”. This div contains the screen and all the buttons.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Calculator</title>
<link rel="stylesheet" type="text/css" href="calculator.css">
<script src="calculator.js"></script>
</head>
<body>
<h1>(Your name's) Calculator</h1>
<div class="container">
<input type="text" id="screen" disabled>
<div class="button-row">
<button class="button" onclick="addNumber('1')">1</button>
<button class="button" onclick="addNumber('2')">2</button>
<button class="button" onclick="addNumber('3')">3</button>
<button class="button" onclick="addOperator('+')">+</button>
</div>
<div class="button-row">
<button class="button" onclick="addNumber('4')">4</button>
<button class="button" onclick="addNumber('5')">5</button>
<button class="button" onclick="addNumber('6')">6</button>
<button class="button" onclick="addOperator('-')">-</button>
</div>
<div class="button-row">
<button class="button" onclick="addNumber('7')">7</button>
<button class="button" onclick="addNumber('8')">8</button>
<button class="button" onclick="addNumber('9')">9</button>
<button class="button" onclick="addOperator('*')">*</button>
</div>
<div class="button-row">
<button class="button" onclick="addNumber('0')">0</button>
<button class="button" onclick="addOperator('/')">/</button>
<button class="button" onclick="calculate()">=</button>
</div>
<div class="button-row">
<button class="clear-button" onclick="clearScreen()">Clear</button>
</div>
</div>
</body>
</html>
The section of our code includes the standard HTML boilerplate, as well as some additional elements. The <meta>
tags define the character set, compatibility, and viewport of the webpage. The <title>
tag sets the title of the webpage, which appears in the browser tab. The <link>
tag links to an external CSS file for styling, and the <script>
tag links to an external JavaScript file for the calculator's functionality
After the head, the <body>
tag is where the visible content of the webpage goes. In this case, we have an <h1>
tag that displays the title of the calculator. The <div>
tag with a class of "container" is where we will put the rest of the calculator's HTML code.
Inside the container <div>
, we have a text input field with an id
of "screen". This is where the calculator will display the user's input and output. Below that, we have several <button>
tags that the user can click to input numbers and operators. Each button has a class
of "button" for styling purposes.
The onclick
attribute is used to call specific JavaScript functions when a button is clicked. For example, the first button calls the addNumber()
function with an argument of '1', which will add the number 1 to the input field.
At the bottom of the container <div>
, there is a clear button that will call the clearScreen()
function when clicked.
Overall, this HTML code sets up the basic structure of the calculator app and provides the necessary elements for the JavaScript code to interact with.
CSS Code
When designing the calculator app, I recognized that its visual appearance was just as important as its functionality. Therefore, I used CSS to give the HTML elements a specific look and feel.
To begin, I set styles for the <body> and container elements to establish the overall layout and appearance of the calculator app. I employed the max-width, margin, padding, background-color, box-shadow, and border-radius properties to achieve this.
Next, I concentrated on the screen and buttons to give them a specific layout, font size, and color. I set styles for the #screen, .button, and .clear-button classes to make them visually appealing and easy to use.
To make the buttons more interactive, I added hover and active states by using the :hover
and :active
pseudo-classes. This added an extra level of user engagement to the calculator app.
Finally, I added a media query to make the calculator app responsive and look good on smaller screens. This made sure that users could access the calculator app on their mobile devices without any issues.
Here’s the CSS code I used to style the calculator app:
body {
background-color: #f5f5f5;
font-family: 'Montserrat', sans-serif;
text-align: center;
}
.container {
max-width: 500px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
border-radius: 10px;
display: grid;
grid-gap: 10px;
position: relative;
}
.container:before {
content: '';
display: block;
position: absolute;
top: -20px;
left: -20px;
width: calc(100% + 40px);
height: calc(100% + 40px);
border: 2px solid #ddd;
border-radius: 15px;
box-sizing: border-box;
pointer-events: none;
}
#screen {
font-size: 1.5rem;
text-align: right;
padding: 10px;
border: none;
border-radius: 5px;
box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2);
background-color: lightgray;
margin: 0 auto;
width: 100%;
max-width: 300px;
margin-bottom: 20px;
}
.button {
font-size: 1.8rem;
padding: 20px;
border: none;
border-radius: 5px;
background-color: #0b162a;
color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
cursor: pointer;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #c83803;
}
.button:active {
box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2);
background-color: #c83803;
}
.clear-button {
font-size: 1.5rem;
padding: 15px;
border: none;
border-radius: 5px;
background-color: #c83803;
color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
cursor: pointer;
transition: background-color 0.3s ease;
}
.clear-button:hover {
background-color: #0b162a;
}
.clear-button:active {
background-color: #0b162a;
}
@media only screen and (max-width: 480px) {
.container {
max-width: 300px;
}
#screen {
font-size: 2rem;
margin-bottom: 10px;
padding-right: 3px;
border-radius: 100px;
background-color: lightgray;
}
.button {
font-size: 2rem;
height: 75px;
padding: 12px;
width: 43px;
touch-action: manipulation;
}
.clear-button {
font-size: 1.5rem;
padding: 15px;
border: none;
border-radius: 5px;
background-color: #c83803;
color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
cursor: pointer;
transition: background-color 0.3s ease;
touch-action: manipulation;
}
.button-row {
flex-wrap: wrap;
}
}
In the first half of this blog post, we discussed how to create a basic calculator web app’s structure using HTML and how to style it using CSS. Now, let’s dive into adding functionality to our calculator app using JavaScript. Make sure to add the JavaScript code to a separate file and link it to your HTML file created earlier.
JavaScript Code
Building my calculator app, the JavaScript code is responsible for handling the logic behind the calculations. In my app, I used JavaScript to store and manipulate the values entered by the user, as well as perform the actual calculations.
First, I declared four variables: num1, num2, operator, and result. These variables are used to store the two numbers entered by the user, the operator that the user selected (+, -, *, or /), and the result of the calculation.
let num1 = '';
let num2 = '';
let operator = '';
let result = '';
Next, I created three functions: addNumber()
, addOperator()
, and calculate()
.
The addNumber()
function is called when the user clicks on one of the number buttons. It takes the number as an argument and adds it to either num1
or num2
, depending on whether an operator has been selected or not. The function then updates the calculator screen with the new value using the document.getElementById()
method and the addCommas()
function.
function addNumber(number) {
if (operator == '') {
num1 += number;
document.getElementById('screen').value = addCommas(num1);
} else {
num2 += number;
document.getElementById('screen').value = addCommas(num2);
}
}
The addOperator()
function is called when the user clicks on one of the operator buttons. It takes the operator as an argument and sets the operator
variable to that value.
function addOperator(op) {
operator = op;
}
The calculate()
function is called when the user clicks on the equals button. It uses a switch statement to determine which operator was selected and performs the appropriate calculation using parseInt()
to convert the strings to numbers. The result is then stored in the result
variable and displayed on the calculator screen using the addCommas()
function.
function calculate() {
switch (operator) {
case '+':
result = parseInt(num1.replace(/,/g, '')) + parseInt(num2.replace(/,/g, ''));
break;
case '-':
result = parseInt(num1.replace(/,/g, '')) - parseInt(num2.replace(/,/g, ''));
break;
case '*':
result = parseInt(num1.replace(/,/g, '')) * parseInt(num2.replace(/,/g, ''));
break;
case '/':
result = parseInt(num1.replace(/,/g, '')) / parseInt(num2.replace(/,/g, ''));
break;
}
document.getElementById('screen').value = addCommas(result);
}
The clearScreen()
function is called when the user clicks on the clear button. It resets all variables to their initial values and clears the calculator screen.
function clearScreen() {
num1 = '';
num2 = '';
operator = '';
result = '';
document.getElementById('screen').value = '';
}
Lastly, we have the addCommas()
function, which is a helper function used to format numbers on the calculator screen. It takes a number as an argument and adds commas to it to make it more readable. It does this by converting the number to a string and using a regular expression to add commas at every third digit.
function addCommas(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
These functions work together to create a simple but functional calculator app. They allow the user to input numbers and operators, perform calculations, and clear the screen when needed.
Here is the full code for you to check out. Try your best to understand before implementing it in your own code and Google whenever needed:
let num1 = '';
let num2 = '';
let operator = '';
let result = '';
function addNumber(number) {
if (operator == '') {
num1 += number;
document.getElementById('screen').value = addCommas(num1);
} else {
num2 += number;
document.getElementById('screen').value = addCommas(num2);
}
}
function addOperator(op) {
console.log('addOperator called with operator:', op);
operator = op;
}
function calculate() {
switch (operator) {
case '+':
result = parseInt(num1.replace(/,/g, '')) + parseInt(num2.replace(/,/g, ''));
break;
case '-':
result = parseInt(num1.replace(/,/g, '')) - parseInt(num2.replace(/,/g, ''));
break;
case '*':
result = parseInt(num1.replace(/,/g, '')) * parseInt(num2.replace(/,/g, ''));
break;
case '/':
result = parseInt(num1.replace(/,/g, '')) / parseInt(num2.replace(/,/g, ''));
break;
}
document.getElementById('screen').value = addCommas(result);
}
function clearScreen() {
num1 = '';
num2 = '';
operator = '';
result = '';
document.getElementById('screen').value = '';
}
function addCommas(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Testing and Debugging
After completing the development of the calculator app, I tested it to make sure that it works as expected. I tested the app for different inputs, such as addition, subtraction, multiplication, and division. I also tested the app for boundary cases, such as dividing by zero and entering invalid characters. Through testing, I was able to identify and fix several bugs in the app, including issues with the screen not updating correctly and unexpected results for certain inputs.
To debug the app, I used the browser console to log values and messages at different points in the code. This helped me to identify the source of the bugs and make necessary changes to the code.
Deployment
Once I was satisfied with the functionality of the app, I deployed it to GitHub Pages. To deploy the app, I created a repository on GitHub and pushed the code to the repository. Then, I enabled GitHub Pages for the repository and selected the main branch as the source for the deployment. Finally, I tested the deployed app to make sure that it works correctly and is accessible to users.
The calculator app can be accessed by users through the GitHub Pages URL. To view mine, check it out here.
Conclusion
In this blog post, I walked through the process of creating a basic calculator web application using HTML, CSS, and JavaScript. We started by creating the HTML structure of the app, then moved on to styling it with CSS, and finally added functionality with JavaScript. We explained each step of the process in detail and provided code snippets for readers to follow along.
By the end of this post, you should have a good understanding of how to create a basic web application and how to use HTML, CSS, and JavaScript to bring it to life. It’s important to note that this is just a starting point and there’s much more to learn about web development.
Additional Resources:
If you’re interested in learning more about web development, here are some additional resources that may be helpful:
- W3Schools: A popular online resource for learning HTML, CSS, and JavaScript. It offers tutorials, reference guides, and interactive exercises.
- MDN Web Docs: A comprehensive resource for web developers, maintained by Mozilla. It includes documentation on HTML, CSS, JavaScript, and other web technologies.
- Codecademy: An online learning platform that offers interactive courses in web development, including HTML, CSS, and JavaScript.
- Udemy: An online learning marketplace that offers courses in web development, including HTML, CSS, and JavaScript.
- Stack Overflow: A question-and-answer community for programmers, where you can find answers to common web development problems and get help from other developers.
By exploring these resources and continuing to practice, you’ll be well on your way to becoming a skilled web developer. Good luck, and happy coding!