Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,150,637 members, 7,809,392 topics. Date: Friday, 26 April 2024 at 08:43 AM

Creating A Simple Calculator With Raw Javascript - Webmasters - Nairaland

Nairaland Forum / Science/Technology / Webmasters / Creating A Simple Calculator With Raw Javascript (6471 Views)

Trick: How To Make A Simple Calculator Using Notepad. / 10 Things You Must Know And Have Before Creating A Blog / Tips For Creating A Successful Blog/Site (2) (3) (4)

(1) (Reply) (Go Down)

Creating A Simple Calculator With Raw Javascript by dhtml(m): 10:42am On Jul 12, 2014
We have already completed part 1 of our javascript tutorial here https://www.nairaland.com/1789014/javascript-tutorial-scratch-brought-
We are now going to do a small workshop before proceeding to part 2. The idea of this calculator is to show how javascript is used in real life everyday programming.
This class is going to make use some javascript functionalities that are beyond the scope of the part 1 tutorial, but i shall try to explain as we go. At the end of this, we shall now go into part 2 of the tutorial (which will feature jQuery), and the worshop of that part 2 shall be more applications, and we shall build at least one simple javascript event-driven game maybe tetris or something really simple.

Attached is a screenshot of the calculator, and also attached is the source code used to generate the layout.
Every other thing from here will be javascript. So fasten your seat belt (and if it is the new automatic type that we find in commercial buses now adays, just wear am over your chest) make we carry go.

Re: Creating A Simple Calculator With Raw Javascript by adewasco2k(m): 11:07am On Jul 12, 2014
leggo
Re: Creating A Simple Calculator With Raw Javascript by Nobody: 11:19am On Jul 12, 2014
following.
Re: Creating A Simple Calculator With Raw Javascript by blueyedgeek(m): 11:38am On Jul 12, 2014
var followingThread = true;

1 Like

Re: Creating A Simple Calculator With Raw Javascript by dhtml(m): 12:38pm On Jul 12, 2014
This calculator is a very good introduction to event-driven programming. The first aspect of the calculator we are going to code is the keypad of the calculator.
The keypad may look simple to a beginner, you may think maybe an ordinary html textbox will do it, but that is wrong. We are using a DIV element for good reason too. A DIV element cannot be typed into like a textbox, true. But in event-driven programming, we can capture keys that are pressed on the keyboard and respond to them appropriately, and that is what we are going to do now.

To a programmer, the keyboard scan keys are very important, these are codes that are attached to every key on the keyboard. I shall post a reference here for that.

Re: Creating A Simple Calculator With Raw Javascript by dhtml(m): 12:44pm On Jul 12, 2014
You are not meant to memorize the keyboard scan code, and in case i forgot to mention it, the keyboard scan code is used generally in programming, so if you go to c,c++,c#,java,visual basic and others as long as keyboard interaction is used.
Nobody needs to memorize the scan codes, but it is good to have a reference.

An example of how to check the keyboard scan code:

keyboard.html
<html>
<head>
<title>Javascript Keyboard</title>
<script>
function keypad(evt) {
if(!evt) {evt=window.event;}
var key=evt.keyCode;
s=String.fromCharCode(key);
document.getElementById('calculator').innerHTML='Last Keycode is '+key+'<br/>'+'And the character is '+s;
}

window.onload=function() {
document.getElementById('calculator').onkeyup = keypad;
}
</script>
</head>
<body id='calculator'>
Press any key at all on your keyboard to get started!
</body>
</html>


Events (2)
=> load: this event is triggered when an object loads. An example here is when the window loads.
This is equivalent to $(function() {}) or $.ready(function() {}) in jQuery.
=> keyup: this is triggered when a key is pressed on the keyboard. It generates a keyboard scan code.

Functions (2)
=> keypad: this is a custom function that is used to process the keyup event here to capture the event, and detect the key that was pressed.
==> String.fromCharCode: converts keyboard scan code into the appropriate character.
Re: Creating A Simple Calculator With Raw Javascript by Nastydroid(m): 12:51pm On Jul 12, 2014
*spreads mat*
Re: Creating A Simple Calculator With Raw Javascript by dhtml(m): 1:21pm On Jul 12, 2014
Let us now review that keyboard.html more critically by first adding line numbers:

1. <html>
2. <head>
3. <title>Javascript Keyboard</title>
4. <script>
5. function keypad(evt) {
6. if(!evt) {evt=window.event;}
7. var key=evt.keyCode;
8. s=String.fromCharCode(key);
9. document.getElementById('calculator').innerHTML='Last Keycode is '+key+'<br/>'+'And the character is '+s;
10. }
11. window.onload=function() {
12. document.getElementById('calculator').onkeyup = keypad;
13. }
14. </script>
15. </head>
16. <body id='calculator'>
17. Press any key at all on your keyboard to get started!
18. </body>
19. </html>


document.getElementById
The body is given an id of calculator. To access the body through javascript using this ID,
document.getElementById('calculator').
Every HTML element has an innerHTML property which can be set or retrieved just like any other variable.

Events and Event Handlers
Events are occurences that happen in a programming language and that can be detected by the language such as when you press a key, click the mouse, even close the browser window.

Looking at line 11: document.getElementById('calculator').onkeyup = keypad;
onkeyup is an event (called keyup) which is triggered by pressing any key at all on the keyboard. keypad is the event handler, this means that when a key is pressed on the keyboard, keypad function which is defined on line 5 is called.

keypad function
When an event handler is triggered by normal browsers (excluding internet explorer), the event object is passed to the event handler, in this case evt.
However, internet explorer does not do this, instead internet explore provides the most recent event
as an object under the windows object, that is why line 6 exists.
For internet explorer, evt will be false on line 5, line 6 will detect this and update the value of evt to window.event.

String.fromCharCode
This is a function under the String method that will convert a keyboard scan code into the appropriate character. It was used on line 8 of the code.
Re: Creating A Simple Calculator With Raw Javascript by dhtml(m): 1:26pm On Jul 12, 2014
Assuming the code above is understood, you can now progress to the next stage, creating the screen of the calculator, and allowing users to be able to type numbers on it from the keyboard. I shall attach it for easy download as well.

screen.html
<html>
<head>
<title>Javascript Calculator Keypad</title>
<script>
function keypad(evt) {
if(!evt) {evt=window.event;}
var key=evt.keyCode;

keypad_process_key(key);

//cancel bubble
if (evt.stopPropagation) evt.stopPropagation();
if (evt.cancelBubble!=null) evt.cancelBubble = true;
}

//process the keyboard scan code to affect the calculator display
function keypad_process_key(key) {
var buffer=document.getElementById('console').innerHTML; //get current console data
if(buffer==0) {buffer='';} //reset buffer if it is empty (0 as value)

document.title='Last Keycode is '+key; //show the current scan code in the titlebar
switch(key) {
case 8: //backspace is pressed
buffer=buffer.substr(0,buffer.length-1); //delete last character in the buffer
break;

case 46: //delete is pressed
buffer=''; //we empty the buffer
break;


default:
if(key>47 && key <59) {
s=String.fromCharCode(key); //get the correct character from the keycode
buffer+=s;
}

}

if(buffer==0) {buffer=0;}

//update the console
document.getElementById('console').innerHTML=buffer;
}

window.onload=function() {
document.getElementById('calculator').onkeyup = keypad;
}
</script>
</head>
<body id='calculator'>

<div id='console'>0</div>

<div style='padding:10px;'>
This is a sample calculator console<br/>
<li>You can press numbers 0 - 9 on your keyboard
<li>You can also press backspace to delete last character
<li>and use delete to clear the screen.
</div>

</body>
</html>

Re: Creating A Simple Calculator With Raw Javascript by Nastydroid(m): 2:01pm On Jul 12, 2014
Putting a download link is better....anoda tsunami fit go happen
Re: Creating A Simple Calculator With Raw Javascript by Nastydroid(m): 2:03pm On Jul 12, 2014
This question is somehow silly....can it work on my phone browser or it is only for pc?
Re: Creating A Simple Calculator With Raw Javascript by blueyedgeek(m): 2:12pm On Jul 12, 2014
@dhtml, boss. This is too complex for a beginner na. I've just been staring at code and feeling like a dummy embarassed embarassed

What is switch, case, break, String.fromCharCode

I haven't been properly introduced to these beautiful ladies

1 Like

Re: Creating A Simple Calculator With Raw Javascript by dhtml(m): 4:35pm On Jul 12, 2014
Nastydroid: This question is somehow silly....can it work on my phone browser or it is only for pc?
It should work on both, i have not tried it though, it has been awhile that i have used these kind of javascript on mobile.

Example:
if you wish to write a code like this:
var a=5;
if(a==4) {alert('4 boys');}
else if(a==5) {alert('5 babes');}
else {alert('All men');}

You can rewrite that like this:
var a=5;
switch(a) {
case 4:
alert('4 boys');
break;
case 5:
alert('5 babes');
break;
default:
alert('All men');
}

You do understand the keyboard scan codes right?

Let us assume that i wish to find out the character on the keyboard that owns the keyboard scan code 56.

var key=String.fromCharCode(57);
alert(key); //the answer is 9

Now let us assume that we wish to find out the keyboard scan code of the number 9

var char='9';
var key=char.charCodeAt(0);
alert(key); //the answer is 57 which is to be expected.

These functions used here are core javascript functions.
Re: Creating A Simple Calculator With Raw Javascript by dhtml(m): 4:40pm On Jul 12, 2014
Now that you understand the above, let us now show a calculator that has the following working:
0 - 9, . , C, CE, Backspace, and you can also type numbers with the keyboard. And use Del for C, escape for CE and backspace key for backspace.

Please note that i modified the calc.css (so it is different from the first one), and i did some slight adjustments to the html layout.

calculator.html
<html>
<head>
<title>Javascript Calculator</title>
<link rel="stylesheet" href="calc.css">
<script src="keys.js"></script>
</head>
<body id="calculator">

<table class="calc">
<tr><td colspan="5">
<div id="screen">

<div id="formular">5+7+5</div>
<div id="console">0</div>

</div>
</td></tr>
<tr class="cline2">
<td colspan="5">
<input type="button" onclick = 'keypad_process_key( 8 );' value=" Backspace ">
<input type="button" onclick="keypad_process_key(27)" value="CE">
<input type="button" onclick="keypad_process_key(46)" value="C">
</td></tr>
<tr class="cline">
<td><input type="button" value="7" onclick="cdigit(this)"></td>
<td><input type="button" value="8" onclick="cdigit(this)"></td>
<td><input type="button" value="9" onclick="cdigit(this)"></td>
<td><input type="button" value="/"></td>
<td><input type="button" value="sqrt"></td>
</tr>
<tr class="cline">
<td><input type="button" value="4" onclick="cdigit(this)"></td>
<td><input type="button" value="5" onclick="cdigit(this)"></td>
<td><input type="button" value="6" onclick="cdigit(this)"></td>
<td><input type="button" value="*"></td>
<td><input type="button" value="%"></td>
</tr>
<tr class="cline">
<td><input type="button" value="1" onclick="cdigit(this)"></td>
<td><input type="button" value="2" onclick="cdigit(this)"></td>
<td><input type="button" value="3" onclick="cdigit(this)"></td>
<td><input type="button" value="-"></td>
<td><input type="button" value="1/X"></td>
</tr>
<tr class="cline">
<td><input type="button" value="0" onclick="cdigit(this)"></td>
<td><input type="button" value="+/-" onclick="dosign()" ></td>
<td><input type="button" value="." onclick="keypad_process_key(190)" ></td>
<td><input type="button" value="+"></td>
<td><input type="button" value="="></td>
</tr>
</table>

</body>
</html>


calc.css
* {font:14px tahoma;}
.calc {border:1px solid #cccccc;background:#ceceff;}
.calc .cline input{font:12px tahoma;width:50px;height:40px;}
.calc .cline2 input{font:12px tahoma;width:90px;height:40px;}
.calc #screen {width:275px;text-align:right;background:#ffffff;height:47px;background:url('bg.png');}

#formular {height:17px;font-size:11px;line-height:4.5mm;padding-right:3px;}
#console{height:30px;font-size:24px;line-height:8mm;padding-right:3px;}

keys.js
/*
shortcut function for document.getElementById
instead of document.getElementById('calculator') you can now use el('calculator')
*/
function el(objectID) {return document.getElementById(objectID);}

function getScanCode(str) {return str.charCodeAt(0)}

function cdigit(elm) {
key=elm.value;
keyCode=getScanCode(key);
keypad_process_key(keyCode);
}

function keypad(evt) {
if(!evt) {evt=window.event;}
var keyCode=evt.keyCode;

keypad_process_key(keyCode);

//cancel bubble
if (evt.stopPropagation) evt.stopPropagation();
if (evt.cancelBubble!=null) evt.cancelBubble = true;
}

//process the keyboard scan code to affect the calculator display
function keypad_process_key(keyCode) {
var buffer=el('console').innerHTML; //get current console data
if(buffer==='0') {buffer='';} //reset buffer if it is empty (0 as value)

switch(keyCode) {
case 8: //backspace is pressed
if(buffer!='') {
buffer=buffer.substr(0,buffer.length-1); //delete last character in the buffer
}
break;

case 46: //delete is pressed
buffer=''; //we empty the buffer
el('formular').innerHTML='';
break;

case 190: //. is pressed
if(buffer==''||buffer=='0') {buffer='0.';}
else if(buffer.indexOf('.')==-1) {buffer+='.';}
break;

case 27: //escape is pressed
buffer=''; //we empty the buffer
break;

default:
if(keyCode>47 && keyCode <59) {
s=String.fromCharCode(keyCode); //get the correct character from the keycode
buffer+=s;
}

}

if(buffer=='') {buffer=0;}

//update the console
el('console').innerHTML=buffer;
}

window.onload=function() {
el('calculator').onkeyup = keypad;
}

I am expecting a number of questions here which i shall answer, but if you skip all the stuffs above, you will not really understand this aspect. So if there is something you are seeing in this code that you have also seen in the previous codes, it is better you start addressing it from the previous codes above.
Every program is made up of components, the same thing with this, it was done in parts and step-wise. I did not just start typing the codes from the begining to the end.

Re: Creating A Simple Calculator With Raw Javascript by Nobody: 8:45pm On Jul 12, 2014
dhtml nothing happened when I run the keyboard.html on my browser.
Re: Creating A Simple Calculator With Raw Javascript by Nobody: 9:12pm On Jul 12, 2014
dhtml the mathematical operators are not working calculator.html, maybe because you didn't add an onclick to them.
Re: Creating A Simple Calculator With Raw Javascript by dhtml(m): 9:56pm On Jul 12, 2014
I explained in i think my last post that the arithmetic operators are not yet working.

Now that you understand the above, let us now show a calculator that has the following working:
0 - 9, . , C, CE, Backspace, and you can also type numbers with the keyboard. And use Del for C, escape for CE and backspace key for backspace.
To quote myself, I hope you have understood the codes above at least to an extent? The next phase remaining is to now make the mathematical operators work.
Re: Creating A Simple Calculator With Raw Javascript by Nobody: 10:02pm On Jul 12, 2014
Okay, what about this one.

phatjoe50: dhtml nothing happened when I run the keyboard.html on my browser.
Re: Creating A Simple Calculator With Raw Javascript by dhtml(m): 10:24pm On Jul 12, 2014
I just tested the calculator and it works in the following browsers:
1. The evil internet explorer
2. mozilla firefox (latest)
3. Netscape Navigator 9.0 (i still have it),
4. Opera
5. google chrome
6. maxthon
7. crazy browser (and i am not crazy)
8. safari
9. Blackberry native browser (both keypad and touch-screen keyboard worked)
10. Blackberry opera mini
11. Ipad native browser

As for the keyboard.html, i dont know why it fails to work on your browser BTW which browser did you test it on?
Re: Creating A Simple Calculator With Raw Javascript by Nobody: 10:42pm On Jul 12, 2014
Chrome, Mozilla and IE.
Re: Creating A Simple Calculator With Raw Javascript by dhtml(m): 11:38pm On Jul 12, 2014
phatjoe50: Chrome, Mozilla and IE.
Maybe you should just leave the keyboard alone and focus on the main calculator itself. It might be due to many reasons, plugins and all sorta things.


We now come to the end of the calculator tutorial, i now present a 'simple' pure javascript calculator attached below.

I am expecting questions most certainly, i know there shall be plenty, and i also know that the next class should answer most of those questions.

And oh, you might test the calculator online here - http://.net/calc/

Re: Creating A Simple Calculator With Raw Javascript by dhtml(m): 11:54pm On Jul 12, 2014
I hope you guys are properly backing up these tutorials, just in case them disappear again!

And so, the part 2 of the tutorial is kicking off here, leave this calculator alone if it is bugging you. After the second part of the tutorial, the calculator will make sense and will look much more easier.

https://www.nairaland.com/1810544/javascript-tutorial-scratch-brought-#24648523
Re: Creating A Simple Calculator With Raw Javascript by Nobody: 11:59pm On Jul 12, 2014
OK sir!
Re: Creating A Simple Calculator With Raw Javascript by dhtml(m): 12:01am On Jul 13, 2014
Hope you people are backing up the thread in case. . . . lipsrsealed lipsrsealed lipsrsealed (no be my mouth talk am o)
Re: Creating A Simple Calculator With Raw Javascript by tohero(m): 2:14pm On Jul 19, 2014
dhtml: Hope you people are backing up the thread in case. . . . lipsrsealed lipsrsealed lipsrsealed (no be my mouth talk am o)
I just pressed #9 on my opera mini. Nt only because of the tsunami but m stil a novice to javascipt.
smiley
Is there any PDF for this tut bro?
Tanks. I already tot of doing something lyk this when I stat to learn JS
Re: Creating A Simple Calculator With Raw Javascript by dhtml(m): 3:31pm On Aug 29, 2014
I shall make a pdf tutorial available much later. However, you are visit www.dhtmlhub.com to connect to other developers.
Re: Creating A Simple Calculator With Raw Javascript by Nobody: 8:18am On Jul 06, 2015
Finally, here is the complete revised working calculator

Re: Creating A Simple Calculator With Raw Javascript by Nmeri17: 2:19pm On Jan 13, 2016
dhtml18:
Finally, here is the complete revised working calculator
Ah! Oga... You too much cheesy. I just noticed you added even android event listeners.

I don't get this part tho

function keypad(evt) {
if(!evt) {evt=window.event;}
var keyCode=evt.keyCode;

keypad_process_key(keyCode);

//cancel bubble
if (evt.stopPropagation) evt.stopPropagation();
if (evt.cancelBubble!=null) evt.cancelBubble = true;
}

Care to explain?

And why is dhtml extreme .com striped off from every where it is being written undecided undecided
Re: Creating A Simple Calculator With Raw Javascript by Nobody: 5:37pm On Jan 13, 2016
Nmeri17:
Ah! Oga... You too much cheesy. I just noticed you added even android event listeners.

I don't get this part tho

function keypad(evt) {
if(!evt) {evt=window.event;}
var keyCode=evt.keyCode;

keypad_process_key(keyCode);

//cancel bubble
if (evt.stopPropagation) evt.stopPropagation();
if (evt.cancelBubble!=null) evt.cancelBubble = true;
}

Care to explain?

And why is dhtml extreme .com striped off from every where it is being written undecided undecided

The evt parameter is "auto passed" by Javascript since it is called on the window.onload function, the check on evt is simply because old browsers, notably IE would not pass the event object as expected since it uses window.event to denote it's event... Key code is just getting the key pressed by the user, since it is a calculator - it has to be extremely aware .

For the event.stopPropagation and the rest, you can check this http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing
Re: Creating A Simple Calculator With Raw Javascript by Nmeri17: 8:57pm On Jan 13, 2016
Jregz:
.....
OK. thanks for the SO thread but there's no higher element for the event to propagate to naa. It's just the table datas there that events were registered to. Why bother terminating propagation when it's not bubbling to the calculator div? Abi the calculator keyup event is same as "click"? BTW, what's the use of that calculator event anyways

Secondly, are you saying the evt part is uncalled for if I'm not referencing older browsers?
PS: please say yes cheesy

Besides OP bro, your work have been easier if you simply used div tags or buttons for the calculator buttons then arrange it using display: table-cell; in CSS3. Maybe CSS3 never commot sha when the topic was created. same with the screen: no need for that png--just use background gradients.

(1) (Reply)

BLOGGERS: Google Punishes Sites With Pop-up Adverts / How To Earn Maximum Amount Of Profit From Your Blog In 2019 / Is It Advisable To Blog With A Phone?

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 79
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.