Enough JavaScript to get you Started : #20 Making your first project

Enough JavaScript to get you Started : #20 Making your first project

ยท

8 min read

โ€œ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:

  1. Playing with DOM
  2. Adding Event Listeners
  3. Conditionals
  4. Looping constructs
  5. Error handling
  6. 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 ๐Ÿ˜


Source code


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 โค

Hey , Let' Connect๐Ÿ‘‹

Twitter / Github