Building a Simple Calculator Project from Scratch
Building a Simple Calculator Project from Scratch
Creating a simple calculator is a great way to start your journey into web development. This project will introduce you to basic HTML, CSS, and JavaScript concepts. By the end of this tutorial, you'll have a working calculator that can perform basic arithmetic operations. Additionally, I'll guide you through turning your web-based calculator into a Progressive Web App (PWA) and packaging it as an Android app.
Step 1: Setting Up the Project
First, we'll set up the basic structure for our calculator project.
1. Create the Project Directory
Create a new directory for your project. This will contain all the files for your calculator.
mkdir SimpleCalculator
cd SimpleCalculator
2. Create HTML File
Create an index.html file in your project directory. This file will contain the structure of your calculator.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calculator">
<input type="text" id="display" disabled>
<div class="buttons">
<button class="btn" onclick="clearDisplay()">C</button>
<button class="btn" onclick="deleteLast()">DEL</button>
<button class="btn" onclick="appendToDisplay('%')">%</button>
<button class="btn" onclick="appendToDisplay('/')">/</button>
<button class="btn" onclick="appendToDisplay('7')">7</button>
<button class="btn" onclick="appendToDisplay('8')">8</button>
<button class="btn" onclick="appendToDisplay('9')">9</button>
<button class="btn" onclick="appendToDisplay('*')">*</button>
<button class="btn" onclick="appendToDisplay('4')">4</button>
<button class="btn" onclick="appendToDisplay('5')">5</button>
<button class="btn" onclick="appendToDisplay('6')">6</button>
<button class="btn" onclick="appendToDisplay('-')">-</button>
<button class="btn" onclick="appendToDisplay('1')">1</button>
<button class="btn" onclick="appendToDisplay('2')">2</button>
<button class="btn" onclick="appendToDisplay('3')">3</button>
<button class="btn" onclick="appendToDisplay('+')">+</button>
<button class="btn" onclick="appendToDisplay('0')">0</button>
<button class="btn" onclick="appendToDisplay('.')">.</button>
<button class="btn equal" onclick="calculateResult()">=</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
3. Create CSS File
Create a styles.css file for styling your calculator.
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
margin: 0;
}
.calculator {
width: 300px;
background-color: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
#display {
width: 100%;
height: 40px;
margin-bottom: 10px;
text-align: right;
padding: 10px;
font-size: 18px;
border: 1px solid #ccc;
border-radius: 5px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.btn {
height: 50px;
font-size: 18px;
background-color: #e0e0e0;
border: none;
border-radius: 5px;
cursor: pointer;
}
.btn:hover {
background-color: #d0d0d0;
}
.equal {
grid-column: span 2;
background-color: #4CAF50;
color: white;
}
.equal:hover {
background-color: #45A049;
}
4. Create JavaScript File
Create a script.js file for the calculator's functionality.
function clearDisplay() {
document.getElementById('display').value = '';
}
function deleteLast() {
let display = document.getElementById('display');
display.value = display.value.slice(0, -1);
}
function appendToDisplay(value) {
let display = document.getElementById('display');
display.value += value;
}
function calculateResult() {
let display = document.getElementById('display');
try {
display.value = eval(display.value);
} catch (e) {
display.value = 'Error';
}
}
Step 2: Turning Your Calculator into a PWA
A Progressive Web App (PWA) provides a native app-like experience on the web. We'll convert our calculator into a PWA by adding a manifest file and a service worker.
1. Create Manifest File
Create a manifest.json file in the root of your project.
{
"name": "Simple Calculator",
"short_name": "Calculator",
"start_url": "./index.html",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#000000",
"description": "A simple calculator web application.",
"id": "/",
"icons": [
{
"src": "images/icon-192x192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "images/icon-512x512.png",
"type": "image/png",
"sizes": "512x512"
}
]
}
2. Create Service Worker
Create a service-worker.js file in the root of your project.
const CACHE_NAME = 'calculator-cache-v1';
const urlsToCache = [
'/',
'/index.html',
'/styles.css',
'/script.js'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
return response || fetch(event.request);
})
);
});
3. Register the Service Worker
Add the following code to your index.html file to register the service worker.
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
}).catch(error => {
console.log('Service Worker registration failed:', error);
});
}
</script>
Step 3: Hosting Your Calculator on GitHub Pages
To make your calculator available online, you can host it on GitHub Pages.
1. Create a GitHub Repository
Create a new repository on GitHub and upload all your project files.
2. Enable GitHub Pages
- Go to the repository settings.
- Scroll down to the "GitHub Pages" section.
- Select the branch you want to use (typically
mainormaster), and the root folder. - Save the settings. GitHub will provide a URL for your site.
Step 4: Creating an APK with PWA Builder
1. Go to PWA Builder
Visit PWABuilder.
2. Analyze Your PWA
Enter the URL of your GitHub Pages site and click "Start".
3. Build Your PWA
Follow the prompts to ensure your PWA is configured correctly and generate the APK.
Conclusion
You've successfully built a simple calculator, turned it into a PWA, hosted it on GitHub Pages, and created an APK using PWA Builder. This project introduced you to essential web development and PWA concepts, providing a solid foundation for more advanced projects.
Feel free to share your experience or ask questions in the comments below. Happy coding!
Comments
Post a Comment
Thank you for your time!