Whoever is learning JavaScript and making projects in JavaScript then it is very important to make a calculator project because you will learn a lot about JavaScript from this project. So, in this article, I am going to teach you step-by-step how you can create an iPhone Calculator using HTML, CSS, and JavaScript.
Along with learning the iPhone Calculator project in JavaScript, I am also going to provide the source code. If you already know JavaScript and you only want the source code of the iPhone Calculator, then you can directly copy the source code from here.
![iPhone Calculator using HTML, CSS and JavaScript](https://codingprojects.online/wp-content/uploads/2023/11/iPhone-Calculator-using-HTML-CSS-and-JavaScript.webp)
Algorithm Of iPhone Calculator
Before making the Calculator, we will understand its algorithm because it is very important to understand its algorithm whether the project is easy or complicated.
- User Input:
- Take numbers and operators from the user.
- Calculate:
- When the user enters an operator, calculate using the given numbers.
- Display Result:
- Show the result to the user.
This is the simple and short algorithm for our calculator project and now we have to convert this algorithm into code. So let’s do it.
Prerequisites to Make an iPhone Calculator
To create an iPhone Calculator using HTML, CSS, and JavaScript you need:
- Basic knowledge of HTML for structuring the iPhone Calculator interface.
- CSS knowledge for styling and layout.
- Undestanding of JavaScript for handling calculation logic and updating the display.
- A code editor for writing and testing code.
iPhone Calculator HTML Code
Here is the HTML code for the iPhone Calculator, you can easily understand the code because I have added comments in the code at every step.
And you can also copy the entire code with the “Copy” button.
<!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">
<title>Calculator using HTML, CSS, and JS</title>
<!-- Link to Google Fonts for styling -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<!-- Link to external CSS file -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<section>
<div class="main">
<div class="container">
<!-- Input field for geting the input and displaying the calculator result -->
<div class="row">
<input type="text" id="result" placeholder="0">
</div>
<!-- Calculator buttons arranged in rows -->
<div class="row">
<!-- Button to clear the input (AC) -->
<button class="btn light_btn">AC</button>
<!-- Button to delete the last character (DE) -->
<button class="btn light_btn">DE</button>
<!-- Button for percentage calculation (%) -->
<button class="btn light_btn">%</button>
<!-- Button for division (/) -->
<button class="btn btn_orange" style="font-size: 30px;">/</button>
</div>
<!-- Rows of numeric buttons -->
<div class="row">
<button class="btn">7</button>
<button class="btn">8</button>
<button class="btn">9</button>
<button class="btn btn_orange">*</button>
</div>
<div class="row">
<button class="btn">4</button>
<button class="btn">5</button>
<button class="btn">6</button>
<button class="btn btn_orange">-</button>
</div>
<div class="row">
<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>
<button class="btn btn_orange">+</button>
</div>
<!-- Last row with zero, decimal point, and equals button -->
<div class="row last_row">
<button class="btn">0</button>
<button class="btn">.</button>
<button class="btn btn_orange">=</button>
</div>
<!-- Footer line -->
<div class="footer_line">
<div class="line">
</div>
</div>
</div>
</div>
</section>
<!-- JavaScript file for calculator functionality -->
<script src="script.js" defer></script>
</body>
</html>
HTMLiPhone Calculator CSS Code
Here is the CSS code for the iPhone Calculator, you can easily understand the code because I have added comments in the code at every step.
/* Global styles for the entire document */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
/* Define root-level variables for colors */
:root {
--orange-color: #F69906;
--light-bg-black-color: #383838;
}
/* Styling for the main section of the calculator */
section {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
width: 100%;
}
/* Styling for the main container of the calculator */
.main {
width: 270px;
height: 80vh;
border-radius: 30px;
background-color: rgb(15, 15, 15);
display: flex;
align-items: flex-end;
justify-content: center;
}
/* Styling for the container within the main section */
.container {
width: 100%;
display: flex;
flex-direction: column;
}
/* Styling for rows of buttons in the calculator */
.row {
padding-inline: 20px;
flex-basis: 100%;
display: flex;
justify-content: space-between;
align-items: center;
}
/* Styling for the first button in the last row */
.row.last_row button:first-child {
flex-basis: 47.3%;
border-radius: 30px;
text-align: left;
padding-left: 20px;
}
/* Styling for each button in the calculator */
.row button {
border: none;
outline: none;
flex-basis: 22%;
font-size: 22px;
height: 50px;
border-radius: 50%;
margin-bottom: 10px;
background-color: var(--light-bg-black-color);
color: white;
cursor: pointer;
transition: 0.2s;
}
/* Styling for button hover effect */
.row button:hover {
box-shadow: 0 0 5px #575757;
}
/* Styling for orange-colored buttons */
.btn.btn_orange {
background-color: var(--orange-color);
font-weight: 500;
padding-right: 3px;
}
/* Styling for hover effect on orange-colored buttons */
.btn.btn_orange:hover {
box-shadow: 0 0 5px #d3bb34;
}
/* Styling for light-colored buttons */
.btn.light_btn {
font-weight: 500;
background-color: #acacac;
color: black;
font-size: 20px;
}
/* Styling for hover effect on light-colored buttons */
.btn.light_btn:hover {
box-shadow: 0 0 10px #808080;
}
.btn.light_btn span {
display: inline-block;
transform: rotate(10deg);
}
/* Styling for the footer line */
.footer_line {
display: flex;
justify-content: center;
margin-block: 15px 10px;
}
/* Styling for the line within the footer */
.line {
height: 3px;
border-radius: 10px;
width: 95px;
background-color: #ccc;
}
/* Styling for the calculator result input field */
#result {
overflow: hidden;
height: 100px;
width: 100%;
color: white;
font-size: 50px;
text-align: right;
outline: none;
border: none;
background: transparent;
padding-right: 5px;
font-weight: 300;
}
CSSiPhone Calculator JavasScript Code
Here is our JavaScript code for the iPhone Calculator using JavaScript. You can easily understand the code because I have added comments at each step.
// Select all buttons and the input field
let btns = document.querySelectorAll('button');
let input = document.querySelector('input');
let finaldata;
// Loop through each button and add a click event listener
btns.forEach((e, i) => {
e.addEventListener('click', () => {
// Get the current value in the input field
let inputVal = input.value;
// Get the input value without the last character
let LastCharAfterRemove = inputVal.slice(0, inputVal.length - 1);
// Get the last character of the input value
let LastChar = inputVal[inputVal.length - 1];
// Array of operators
let opr = ['+', '-', '/', '*'];
// Check the button content and perform actions accordingly
if (e.innerHTML == 'AC') {
// Clear the input field if AC (All Clear) button is clicked
input.value = '';
} else if (e.innerHTML == '=') {
// Evaluate the expression and display the result if = (Equals) button is clicked
try {
input.value = eval(inputVal);
} catch (error) {
// Handle errors and display 'Error' if evaluation fails
input.value = 'Error';
}
} else if (e.innerHTML == 'DE') {
// Remove the last character if DE (Delete) button is clicked
input.value = inputVal.slice(0, inputVal.length - 1);
} else {
// Handle numeric and operator buttons
if (opr.includes(e.innerHTML)) {
if (opr.includes(LastChar)) {
// If the last character is an operator, replace it with the new operator
finaldata = LastCharAfterRemove + e.innerHTML;
} else {
// Append the operator to the input value
finaldata = inputVal + e.innerHTML;
}
} else {
// Append numeric buttons to the input value
finaldata = inputVal + e.innerHTML;
}
// Check for multiple decimal points
if (e.innerHTML === '.' && inputVal.includes('.')) {
finaldata = inputVal;
}
// Update the input field with the modified value
input.value = finaldata;
}
});
});
JavaScriptExplanation of iPhone Calculator’s JavaScript code:
- Initialization:
- Select all buttons and the input field from the iPhone calculator webpage.
- User Interaction Loop:
- For each button, set up a click event listener to respond when a button is clicked.
- Button Click Handling:
- When a button is clicked, get the current value from the input field, the last character, and the input without the last character.
- Button Types: AC, Equals, DE:
- If “AC” is clicked, clear the input field.
- If “=” is clicked, evaluate the expression and display the result. Handle errors and show “Error” if the evaluation fails.
- If “DE” is clicked, remove the last character from the input.
- Numeric and Operator Buttons:
- For numeric and operator buttons:
- Check if the last character is an operator.
- Append the operator if needed or replace it with a new one.
- Handle multiple decimal points to avoid errors.
- For numeric and operator buttons:
- Update Input Field:
- Update the input field with the modified value.
Understanding JavaScript Methods and Terms Used in Our Code:
Let’s simplify the JavaScript methods and terms used in our code:
document.querySelectorAll('button')
:- This method selects all HTML elements that are buttons. The selection is based on the ‘button’ tag.
document.querySelector('input')
:- This method selects the first HTML input element found on the page.
forEach((e, i) => { ... })
:- This is a method that iterates over each element in a collection (like a NodeList or array).
e
: Represents the current element in the iteration.i
: Represents the index of the current element in the iteration.
e.addEventListener('click', () => { ... })
:- Adds an event listener to each button element, listening for a ‘click’ event.
- When a button is clicked, the provided function is executed.
let inputVal = input.value;
:- Get the current value of the input field and store
s
it in the variableinputVal
.
- Get the current value of the input field and store
input.value = '';
:- Sets the value of the input field to an empty string, actually clearing it.
try { ... } catch (error) { ... }
:- This is a try-catch block used for error handling.
- The code inside the
try
block is attempted, and if an error occurs, it is caught and handled in thecatch
block.
eval(inputVal)
:- The
eval
function evaluates the input value as a mathematical expression.
- The
inputVal.slice(0, inputVal.length - 1)
:- Uses the
slice
method to remove the last character frominputVal
.
- Uses the
opr.includes(e.innerHTML)
:- Checks if the inner HTML content of the clicked button (
e
) is included in the arrayopr
(array of operators).
- Checks if the inner HTML content of the clicked button (
This is how you can make an iPhone Calculator in JavaScript.
Read this: Dark Mode Toggle using HTML CSS and JavaScript
Read this: How To Create Digital Clock Using HTML CSS and Javascript
Read this: Image Slider using HTML CSS and JavaScript
Read this: Make A Random Quote Generator Using HTML, CSS, and JavaScript
Read this: ToDo List App in JavaScript for Beginners
Conclusion
In this article, I taught you step-by-step how you can create an iPhone calculator project with the help of HTML, CSS, and JavaScript.
The calculator project is a beginner-friendly project and I hope you have understood the steps explained in this article well and I also hope that you will try to make this calculator by yourself.
If you are facing any problem or error while making the iPhone calculator, then you can comment in the comment box given below, and I will reply to you as soon as possible.
To learn HTML, CSS, and JavaScript well, it is very important for you to create projects. The more projects you create, the better your command will be and your logic will increase, so for this, read our other tutorial article.
Thanks.