โKnowledge without Practice is useless, Practice without knowledge is dangerousโ.
-Confucius
Why?
๐ So far we've learnt enough of the basics , though this series is intended to make you aware of basic concepts but if we don't put them in practice then the knowledge we obtained throughout this series will become useless in future
๐ You've invested ample amount of your precious time into this , let's make it worth by putting all these concepts in practical
Making a Calculator
๐ Sounds very clichรฉ right ? but calculator is good for beginners as it covers basic concepts and i don't want absolute beginners to be overwhelmed by intermediate level apps. we'll make them as we go along (for sure !!!)
๐ We'll make a calculator which covers fundamental or core concepts of programming like:
- Playing with DOM
- Adding Event Listeners
- Conditionals
- Looping constructs
- Error handling
- Evaluating mathematical expression
Let's Start
๐ Write this code along with the article open , (i highly recommend don't practice copy pasting ! since you're beginner it's good to write and make mistakes in code)
๐ By practicing this , you'll get lots of errors do let me know in comments if you stumbled upon one ๐
๐ in index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
<input id="input" type="text" placeholder="enter number" />
<br>
<br>
<button>1</button>
<button>2</button>
<button>3</button>
<br>
<button>4</button>
<button>5</button>
<button>6</button>
<br>
<button>7</button>
<button>8</button>
<button>9</button>
<br>
<button>0</button>
<button>+</button>
<button>-</button>
<br>
<button>*</button>
<button>/</button>
<button>=</button>
</div>
<script src="app.js"></script>
</body>
</html>
๐ As you can see , nothing fancy is going on in index.html
we've just added one input field and 15 buttons of different operations
๐ +,-,*,/,=
are operations and 0...9
are numbers.
๐ for the sake of simplicity i'll also provide CSS code for decorating our app with different styles. we're not learning about CSS as it's a separate discussion all together. but surely we want our calculator to look good
๐ in style.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
text-align: center;
height: 100vh;
align-items: center;
justify-content: center;
background: linear-gradient(to right, #dce35b, #45b649);
}
input {
width: 350px !important;
padding: 20px;
font-size: 20px;
border: 1px solid white;
color: white;
user-select: none;
resize: none;
outline: none;
background: transparent;
border-radius: 28px;
}
button {
background: transparent;
padding: 20px;
font-size: 20px;
color: white;
text-align: center;
height: 70px;
width: 70px;
outline: none;
border: 1px solid white;
transition: all .5s;
border-radius: 10px;
margin: 20px;
}
button:hover {
background: white;
color: black;
}
Let's make this calculator alive...
๐ By writing HTML and css we've structured and styled our app , but our app still don't do anything or it doesn't serves purpose
๐ For making it interactive and useful we need ...! yes you're right , JavaScript !!!
๐ in app.js
let input = document.getElementById("input");
document.addEventListener("DOMContentLoaded", () => {
let buttons = document.getElementsByTagName("button");
for (const button of buttons) {
button.addEventListener("click", () => {
if (button.innerText !== "=") {
input.value += button.innerText;
} else {
let expression = input.value;
if (expression) {
try {
input.value = eval(expression);
} catch (error) {
alert("invalid value passed");
}
} else {
alert("empty!!!");
}
}
});
}
});
๐ Okay so there's so many things happening here , let me explain it to you one by one
๐ Firstly , we've selected input
element as we need to get the mathematical expression's value and update input's value every now and then.
๐document.addEventListener("DOMContentLoaded", () => {}
as the event suggests "DOMContentLoaded" , the function will be called as an when the DOM content is loaded in starting.
๐ Next , we're grabbing all the buttons by writing let buttons = document.getElementsByTagName("button");
which will return an array of buttons.
๐ After selecting we're looping through all the buttons with for of
loop and inside the loop we've 2 scenarios ->
-> user enters mathematical expression
-> user enters "="
๐ if user is pressing buttons we want input value to be updated ! hence we've written input.value += button.innerText;
which will append button's text in input element only when user is not pressing =
๐ This if condition will be executed whenever user presses anything except =
and appends text in input element.
๐ now we also want our code to work when user presses =
, so in the else block we'll take input's value by writing let expression = input.value;
and to evaluate this mathematical expression (i.e 2+5-1 = 6) we need to pass this value into eval()
function which takes mathematical expression and returns evaluated answer or error
๐ we've evaluated the input value by writing input.value = eval(expression);
and surrounded it with try{}catch(err){}
block so if error occurs in wrong expression it will alert user. otherwise it'll execute input.value = eval(expression);
which will update input element by filling answer in it ๐
Bonus : Deploying the calculator โจ
๐ Now that our app is ready we can deploy it so that it becomes available world wide.
๐ We'll be using free hosting service known as Netlify
๐ now as we've finished writing it , we'll put this code on Github
๐ Sign up and Create a repository (folder in simple words) with any name in your account
๐ Drag and drop your code to this repository
๐ Head over to Netlify and sign in using GitHub
๐ Now you're presented with a dashboard with 0
websites , click on the New Site from git button
๐ Choose deployment platform as GitHub
๐ Select the repository you've created in GitHub.
๐ Finally , Click on Deploy Site
and boom ! you've just deployed your first website. (you'll find the name of site in dashboard ๐)
Let me know in comment section if you have any doubt or feedback. it's always worth to give time to the thriving developer community :)
Keep Coding โค