MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to make a calculator in JavaScript

The intention of this tutorial is to make readers understand the process of creating a calculator using javascript.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

The javascript involved in this tutorial is not too much extent and is very easy to understand. In the making of this basic calculator we have created 5 javascript functions, the first of which runs when the page loads. However before understanding each function, first you need to setup your html page.

The very first step is to look out for a header so each browser knows what to expect. Headers are not a part of this tutorial. However you can find loads of information by typing 'html headers' into google. So copy the code below and paste it into a blank document and then save it as 'calculator.html' in a folder called 'java-calc'.

Listing 1: Displaying the header information

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>
<TITLE>Basic Calculator</TITLE>
<link type="text/css" rel="stylesheet" href="styles/calculator.css" />

You will notice the last line of the code above is referencing a style sheet (.css) for the reason that because we will need to make a style sheet in orders to display our calculator in a nice orderly format. Next we will insert the 5 functions that run this calculator.

The first thing we need to do is to create an instruction to the users’ browser that we are including some javascript code in the header section of the document. The command is very simple. Go ahead and copy and paste this code to your javacalculator.html document and save it.

<script type="text/javascript"></script>

Now we will need to setup a few variables. These are regarded as 'Global' variables as any function we create will be able to read and write to these global variables, whereas variables that reside only inside a function can only be accessed by that function. A variable is a placeholder for information. These placeholders are written to and read from constantly throughout a program. In this case, we need four (4) global variables. To define them you type the word 'var' (short for variable) then type the name you wish to give to each variable. You can name them whatever you like. Later in your functions, you will refer to these variables by their name. Go ahead and copy/paste the code below into your file and save it.

var Overall="", First="", Second="", Opp="";

One must separate each variable with a commer (,). And when you have finished, the line must end with a semi-colon (;) which tells the browser that the instructional line it has just read is finished and is waiting for the next set of instructions.

The 'First' variable will hold the first set of numbers that is entered using our keypad. The 'Second' holds the set of numbers entered "AFTER" the 'Opp' key is pressed. The 'Opp' variable holds the 'operator' key which is the factor or plus/minus/multiplied/divided the four basic math functions for our calculator and the 'Overall' holds the answer to calculations. It is been set them to 'blank' or 'nill' or 'nothing' by putting '=""' after each one. This is because when the page is loaded and the variables are created we want them to hold no values (be empty). Variables in javascript as with many other languages reside in the computer’s memory (ram).

Onto the functions

One can arrange these functions in whatever order you like as long as they go somewhere in between the <head> and </head> sections of your file. The first one is our "clear" function that is meant to work the same as the 'C' button on any calculator. It resets all the variables. Copy and paste each of the functions into your page.

Listing 2: Illustrates the function Clear()

function Clear()
{
	First = "";
	Second = "";
	Opp = "";
	Overall = "";
	document.getElementById('screen').innerHTML = '0';
}

You will notice that the first line of the function includes the word 'function' followed by the function name (you call this anything you like), and that the function name has two important elements.

  • It does not have a semi-colon (;) after it
  • It has a set of brackets '( )' immediately after the nameEach instruction inside the function ends with a ';' semi-colon and ALL instructions are placed inside curly brackets '{ }'. This tells the browser where the instructions begin and end.

Listing 3: Illustrates function Init()

function Init()
{
	Clear();
}

This function simply calls the previous "clear()" function and we will load it when the page loads.

Listing 4: Illustrates the Functioning of the Numbered Keys

function MyClick($key)
	{ var Display="";
if(Opp == ""){ 
	First = First + $key;
	document.getElementById('screen').innerHTML = First;
	}else{
	Second = Second + $key;
	Display = document.getElementById('screen').innerHTML;
	document.getElementById('screen').innerHTML = First + ' ' + Opp + ' ' + Second;
	     }
		}

This function will be activated when the user clicks any of the numbered keys on the calculator.

Listing 5: Code adds the Operator sign to the ‘Opp’ variable

function Operator($sign)
{       var Display="";
	Opp = $sign;
// See if the first and second factors have values ie: there has already been an equation
if(First != "" && Second != "") DoSum();
	Display = document.getElementById('screen').innerHTML;
	document.getElementById('screen').innerHTML = Display + ' ' + Opp + ' ';
}

This function adds the operator sign to the 'Opp' variable. The value given to the $sign variable inside this function is the value of the key pressed by the user. for eg: the plus ( + ) key. There is another 'IF' statement inside this function which checks to see if the 'First' and 'Second' variables have values already. If they do, then it calls another function 'DoSum()' which does the calculation. That function is next (below). If not, it just adds the operator to the 'Opp' variable only.

Listing 6: Illustrates the function DoSum()

function DoSum()
{ 	
	var string;
	result=0;
if(First != "" && Second != "" && Opp != "")
  {
        string = First + ' ' + Opp + ' ' + Second;
	Overall = eval(string);
	document.getElementById('screen').innerHTML = Overall;
	// Now clear the First, Second and Opp variables for further use
	First = Overall;
	Second = "";
	Opp = "";
}
 }

This final function completes the code. It checks to see if there are 3 values inside the variables. If so, it calculates the answer. It takes the new variable 'string' and adds to that string all 3 values from the global variables (First,Opp and Second) so we end up with one string.

Calculator

Figure 1: Calculator

Conclusion

The article explained the step by step process to come up with a calculator developed in JavaScript. See you next time.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?

Did you like the post?

Help us to keep publishing good contents like this.

SUPPORT US

funded

remaining

[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login