Latest

latest

How to create a simple calculator using vanila Javascript

Thursday 18 January 2018

/ by Fx
Javascript is by no doubt the most popular programming language, it is a very powerful language used for both frontend and backend(Nodejs) website
development. It is the language with the highest number of frameworks which can be used for a number of things.

Alot of beginnes of this language tries to get their hands dirty by building some simple applications like a simple calculator, sometimes they
get stocked with no one to help.

In this tutorial, I will show you one out of the several ways by which you can build a simple calculator using Javascript. I will use  HTML and CSS to make the interface look pretty cool.



This tutorial assumes you have a little foundation in any programming language not necessary Javascript. I Will take it  step by step as I
try to explain what every line of code is doing.

Step 1:
 Build the interface of your  calculator using html and use CSS to make it look awesome.
 I will use the <button> tags to make the calculator buttons and the <input> tag of 'type' text to make the calculator screen, as shown in the code sample


<div id="outer-wrapper">
 <div id="inner-wrapper">
 <div id ="screen-show">
  <input type="text" name="screen" value="0"  id="screen" placeholder="0" disabled="true">
 </div>
 <div id="button-show">
  <button id="7" value="7" onclick="numbers(7)">7</button>
  <button id="8" value="8" onclick="numbers(8)">8</button>
  <button id="9" value="9" onclick="numbers(9)">9</button>
  <button id="divide" value="/" onclick="numbers('/')">/</button>
  <button id="del" value="del" onclick="deleted(del)">DEL</button>
  <br>
  <button id="6" value="6" onclick="numbers(6)">6</button>
  <button id="5" value="5" onclick="numbers(5)">5</button>
  <button id="4" value="4" onclick="numbers(4)">4</button>
  <button id="multiply" value="*" onclick="numbers('*')">x</button>
  <button id="percent" value="%" onclick="numbers('%')">%</button>
  <br>
  <button id="3" value="3" onclick="numbers(3)" >3</button>
  <button id="2" value="2" onclick="numbers(2)">2</button>
  <button id="1" value="1" onclick="numbers(1)">1</button>
  <button id="substrct" value="-" onclick="numbers('-')">-</button>
  <button id="equal" value="=" onclick="numbers('=')">=</button>
  <br>
  <button id="b0" value="0" onclick="numbers(0)">0</button>
  <button id="dot" value="." onclick="dots('.')">.</button>
  <button id="add" value="+" onclick="numbers('+')">+</button>
 </div>
 <div><p>vita!</p></div>
 </div>
 
</div>



Step 2:
On each of these <buttons> tags which I used for my calculator buttons, I have a function 'number()' which is triggered on button click of
the buttons. This function ships in the value of the particular button clicked and this value is stored in a string inside the number function.


function numbers(value){

   
    //wherever this functon is called, get the value of what is on the screen
    var screen=document.getElementById("screen");

    //I used top down approach to code this, read from the elseif statement to enable easy understanding  
    //check if the = sign has been pressed. the variable value is where anything that is pressed is stored. it is passed through the function number()
    if(value=="=")
    {
        //split the input using the split function, which returns it as an array 
        var all=screen.value.split(" ")
        firstpart=parseFloat(all[0]);
        op=all[1];
        secondpart=parseFloat(all[2]);
        
        var screen=document.getElementById("screen");

        if (secondpart==0) 
        {
            screen.value="division by zero!"
        }
        switch(op)
        {   

            case '+':
                result = firstpart + secondpart;
                screen.value= result;
                break;
            case '-':
                result = firstpart - secondpart;
                screen.value= result;
                break;
            case '*':
                result = firstpart*secondpart;
                screen.value= result;
                break;
            case '/':
                result = firstpart / secondpart;
                screen.value= result;

                break;
            case '%':
                result = firstpart % secondpart;
                screen.value= result;
                break;
            default:

            break;
        }
    }

    //if the equals sign wasnt pressed,then the following will be evaluated.
    // checks for what is on the screen and what is pressd
    else if(screen.value =="0" && value=="0")
    {
        return null;
    }

    //it checks for what is on the screen and what is pressed
    else if(screen.value=="0" && !((value=="*" || value=="/" )|| ((value =="+"|| value=="-")|| (value=="%"))))
    {
        screen.value=value;
        //secondpart+=value;
    }
    //if actually a number was pressed, it will save it on an already decleared variable and on the screen
    else if(!((value=="*" || value=="/" )||((value =="+"|| value=="-")|| (value=="%"))))
    {
        screen.value+=value;
        //secondpart+=screen.value;
    }

    //when eventually an operation is pressed,it will build this sting as say 2  *  2 with spaces in between to help me split the array
    else if (op=="0" && ((value=="*" || value=="/" )|| ((value =="+"|| value=="-")|| (value=="%"))))
    {
    //
    //building the string
    screen.value+=" ";
    screen.value+=value;
    screen.value+=" ";
    op=value;
    }
    
    else
    {
        return;
    }
}

The number() functions performs a series of checks to validate the users input, stores it appropriately.

Step 3:
One each of the operations buttons,(buttons for  +,/,*,-), I have a functions attached to them which is triggered on click of the operators
buttons, this function makes the operation to be performed to be saved in the same sting as the numbers. This function also allows for the
deletion of characters.



function deleted(del){
   var screen=document.getElementById("screen");
   screen.value='';
   op=0;
   del=0;
   var firstpart ="0";
   var secondpart = "0";
   var dot=0;
   //console.log(secondpart);
   
  }
   
  function dots(dt){
   //var op= 0;
   if (dot== 0){
   var screen=document.getElementById("screen");
   screen.value+=dt;

   // i changed the value of dot to avoid pressing it two times 
   dot="recoded"
   }
   else
   {
    //returns an empty stuff if you have pressed dot for the first time
    return;
   }
  }

Step 4:
In order to calculate the final result, on the click of the equals(=)sign button, I used a Javascript 'splict' function, to splict the string
at which the characters where stored in to three and then calculate the operation required using a switch statement.

         
var all=screen.value.split(" ");
    firstpart=parseFloat(all[0]);
    op=all[1];
    secondpart=parseFloat(all[2]);


Thanks as I hope this little tutorial helps you. Download and star the full version of this code at my github repository.
Don't forget share because sharing is caring... Follow me on twitter @vita_developer for more wonderful updates
( Hide )
  1. Wow! Great post I must say. Its high time I learnt vanilla js

    ReplyDelete
  2. Want to open your website https://www.mortgage-advice-online.org for calculating my monthly payments. Heard your site is very useful. https://mortgage-advice-online.org

    ReplyDelete
  3. The authority Mathway application. On the off chance that you have an Android gadget, you are in luckiness.adlist24.com

    ReplyDelete

Comment, and tell people what you think

Don't Miss
© all rights reserved
made with by xclusivefx