How to develop an Simple HTML calculator using JavaScript and CSS – Part II

How to develop an Simple HTML calculator using JavaScript and CSS – Part II

How to develop an Simple HTML calculator using JavaScript and CSS – Part I

JavaScript-calculatorWe have learned in our previous part of Simple HTML calculator using JavaScript and CSS about creating the structure of calculator using HTML and CSS. Now in this section we will implement the JavaScript in our structure. Lets start with adding JavaScript file “calculator.js” on the head section of html page.

On top of JavaScript we will declare the variables which are required to complete the functions.

var $ = function(id) { return document.getElementById(id); }; // use to get the element value by id.

var firstval=null; // used to set the first value of calculation
var secondval=null;// used to set the second value of calculation
var operator=null; // used to set active operator user have clicked on
var perform=””;
var flag=false;
var temp = null;
var perenth = false;
var perentheval = false;
// function to add decimal on diplay field with numbers

Now lets create function for each basic keys of our calculator. For decimal button use the below function and it will add the decimal on cal_display value.

var decimal = function(dot){
if (!$(“cal_display”).value.includes(dot)) {
// Append the decimal point
$(“cal_display”).value += dot;
}
}

Below function is used to clear all value from display field using Clear button. We will also reset the variables to default once clear button is clicked.

var clearAll = function(){
$(“cal_display”).value = 0;
firstval = null;
secondval = null;
operator = null;
temp = null;
}
Backspace key will clear the last digit from display area. We will use back function to clear the value on click of backspace button.

var back = function(){

var newtxt=$(“cal_display”).value.slice(0, -1); // remove last digit from display field

if(newtxt==””){

$(“cal_display”).value = 0; // display 0 if no more field exist on display

}else{

$(“cal_display”).value = newtxt; // display remaining text

}

}

changeSign function will be used to set the positive or negative value on calculator.

var changeSign = function(){

if($(“cal_display”).value.charAt(0) == “-“){

$(“cal_display”).value = $(“cal_display”).value.slice(1); // check for negative and change sign

}else{

$(“cal_display”).value = “-” + $(“cal_display”).value; // check for positive and change sign

}

}

Percent function below will calculate the percentage of cal_display value and display on the same on click of percent button.
var percent = function() {

if($(“cal_display”).value!=0){

$(“cal_display”).value = $(“cal_display”).value / 100; // calculate percentage of number on button click

}else{

$(“cal_display”).value += “.0”; // If 0 then will add .0 on button click

}

}
Now we will write all the functions to calculate scientific value of sin, cos, tan, sqrt, log, exponential, square on click of these buttons available in calculator. We will use Math.method of JavaScript to calculate all these values.
// calculate cos on button click

var cos = function() {

$(“cal_display”).value = Math.cos($(“cal_display”).value);
flag = true;

}

// calculate sin on button click

var sin = function() {

$(“cal_display”).value = Math.sin($(“cal_display”).value);
flag = true;

}

// calculate tan on button click

var tan = function() {

$(“cal_display”).value = Math.tan($(“cal_display”).value);
flag = true;

}

// calculate sqrt on button click

var sqrt = function() {

$(“cal_display”).value = Math.sqrt($(“cal_display”).value);
flag = true;

}

// calculate log on button click

var log = function() {

$(“cal_display”).value = Math.log($(“cal_display”).value).toFixed(8);
flag = true;

}

// calculate exponential on button click

var exp = function() {

$(“cal_display”).value = Math.exp($(“cal_display”).value).toFixed(8);
flag = true;

}

// calculate square on button click

var sqr = function() {

$(“cal_display”).value = eval($(“cal_display”).value) * eval($(“cal_display”).value);
flag = true;

}
We have defined most of the functions required on click of respective buttons. Now we will write function which will display the numeric digit value on cal_display once user click the number button. We will store the same value on variable and perform the calculation once user click on keyoperator buttons to perform calculation.

// function to display the numberic value entered by user to perform calculation

var getvalue = function(val){

if(perenth==true){ // will check if user has clicked on perenthasis button or not.

$(“cal_display”).value += val;

}else if($(“cal_display”).value==0||flag==true){

$(“cal_display”).value = val;
flag = false;

}else{

$(“cal_display”).value += val;

}

}

now create a function on window.onload to check if user has clicked number key or not and use getvalue function to display the value.

window.onload = function() {

// get all the input fields named num in array
var buttonnum = document.getElementsByName(‘num’); // we will use document.getElementsByName to check the button name
//and set the innerHTML to the cal_display field.
for (var i = 0, len = buttonnum.length; i < len; i++) {
buttonnum[i].onclick = function (){
getvalue (this.innerHTML);
}
}

}

Once done check your calculator if its displaying the number value correctly or not. It should display all the number value on click in cal_display text field.

Now after the for loop inside window.onload function for num buttons add one more for loop to check if user has clicked main keyoperator or not. If user has clicked main keyoperator button the it will call the function getoperator and store the value of that button to perform calculation later.

// get all the input fields named keyoperator in array to perform various funciton
var buttonkey = document.getElementsByName(‘keyoperater’);
for (var i = 0, len = buttonkey.length; i < len; i++) {
buttonkey[i].onclick = function (){

if(perenth == true){

showperenths(this.value); // show the perenthesis if use has clicked on perenthesis button

}else{

getoperator(this.value);

}
}
}

Now as we have called getoperator and showperenths function we need to create the same outside window.onload function. Use below function to do the same for getoperator and showperenths below that.
// function to get operators and check for available and remoaing value and accordingly calling perform function

var getoperator = function(oper){

if(firstval == null && oper==’pi’){ // check if firstval is blank or not. If user has clicked on operator button previously then firstval will not be null

$(“cal_display”).value = “3.14159265”;

firstval = “3.14159265”;

}else if(firstval == null && oper == ‘equal’){ // check if user has clicked on equal button

var result = performCalculation(”, $(“cal_display”).value, oper);
firstval = result;
secondval = null;
$(“cal_display”).value=result;

}else if(firstval == null){

firstval = $(“cal_display”).value;

}else{

secondval = $(“cal_display”).value; // set the second value for calculation
var result = performCalculation(firstval, secondval, operator); // function to perform calculation
firstval = result; // result will be set inside firstval variable so user can keep doing calculation even after getting the result.
secondval = null;
$(“cal_display”).value=result;
}

flag=true;
operator = oper;

}

Show parenthesis function will check if user has clicked parenthesis button or not. If yes all the value entered after that even the calculation will be displayed on text filed and calculated at the end once user click on equal button. We will use getvalue function created before to display the parenthesis and following numbers and operation.

// show operators if parenthesis is present

var showperenths = function(oper){

if(oper==’divide’){

oper = ‘/’;

}else if(oper==’add’){

oper = ‘+’;

}else if(oper==’substract’){

oper = ‘-‘;

}else if(oper==’multiply’){

oper = ‘*’;

}else if(oper==’pi’){

oper = ‘3.14159265’;

}
//alert(oper);
getvalue(oper);

}
Now add two more for loop inside window.load function for basickey and mathkey values once user click on that buttons like below.
// get all the input fields named basickey in array to perform various funciton
var buttonbasic = document.getElementsByName(‘basickey’);
for (var i = 0, len = buttonbasic.length; i < len; i++) {
buttonbasic[i].onclick = function (){

if(this.value==”back”){ // check for Backspace key

back();

}else if(this.value == “clear”){ // check for clear key

clearAll();

}else if(this.value == “.”){ // check for decimal key

decimal(this.value);

}else if(this.value==”negative”){

changeSign();

}else if(this.value==”parenthopen”){

parenthopen(‘(‘);

}else if(this.value==”parenthclose”){

parenthclose(‘)’);

}

}
}

// get all the input fields named mathkey in array to perform various funciton
var buttonmath = document.getElementsByName(‘mathkey’);
for (var i = 0, len = buttonmath.length; i < len; i++) {
buttonmath[i].onclick = function (){

if(this.value==”per”){ // check for Backspace key

percent();

}else if(this.value==”cos”){ // check for cos

cos();

}else if(this.value==”sin”){ // check for sin

sin();

}else if(this.value==”tan”){ // check for tan

tan();

}else if(this.value==”sqr”){ // check for sqr

sqr();

}else if(this.value==”sqrt”){ // check for sqrt

sqrt();

}else if(this.value==”exp”){ // check for exp

exp();

}else if(this.value==”log”){ // check for exp

log();

}

}
}
We have almost created all the function required for normal calculation however parenthesis one still remain. Use below function to check is parenthesis are open or closed. If open it will display value on text filed else we will do the calculation. We will also create function to do the normal calculation inside performCalculation function based on the operators clicked by user.
// Add open parenthesis

var parenthopen = function(per){

if($(“cal_display”).value==0){

$(“cal_display”).value = per;
perenth = true;

}else if (!$(“cal_display”).value.includes(per)) {
// Append the parenthesis open point
$(“cal_display”).value += ‘*’+per;
perenth = true;

}

}

// Add close parenthesis

var parenthclose = function(per){

if ($(“cal_display”).value.includes(‘(‘) && !$(“cal_display”).value.includes(per)) {
// Append the parenthesis close point
$(“cal_display”).value += per;
perenth = false;
}

}
// show operators if parenthesis is present

var showperenths = function(oper){

if(oper==’divide’){

oper = ‘/’;

}else if(oper==’add’){

oper = ‘+’;

}else if(oper==’substract’){

oper = ‘-‘;

}else if(oper==’multiply’){

oper = ‘*’;

}else if(oper==’pi’){

oper = ‘3.14159265’;

}
//alert(oper);
getvalue(oper);

}

// calculate parenthesis values

var performperenth = function(perenths){
var str = perenths.toString();
if(str.includes(“(“)){




var arr1 = perenths.split(“(“);
var arr2 = arr1[1].split(“)”);

if(arr1[0]!=”){

return eval(arr1[0].concat(eval(arr2[0])));

}else{

return eval(arr2[0]);

}

}else{

return perenths;

}
}

// function to do the calculation on available values

var performCalculation = function(firstval, secondval, operator){

if(operator==’divide’){

temp = parseFloat(performperenth(firstval)) / parseFloat(performperenth(secondval)); //calculate division

}else if(operator==’add’){

temp = parseFloat(performperenth(firstval)) + parseFloat(performperenth(secondval)); //calculate addition

}else if(operator==’substract’){

temp = parseFloat(performperenth(firstval)) – parseFloat(performperenth(secondval)); //calculate substraction

}else if(operator==’multiply’){

temp = parseFloat(performperenth(firstval)) * parseFloat(performperenth(secondval)); //calculate multiply

}else if(operator==’pi’){

temp = parseFloat(performperenth(firstval)) * parseFloat(‘3.14159265’); //calculate pi

}else if(operator==’equal’){

temp = parseFloat(performperenth(secondval)); //show number on click of = button

}

return temp;
}
Below is the complete js files code once again for your reference in case you missed anything.

“use strict”;
var $ = function(id) { return document.getElementById(id); };

var firstval=null;
var secondval=null;
var operator=null;
var perform=””;
var flag=false;
var temp = null;
var perenth = false;
var perentheval = false;
// function to add decimal on diplay field with numbers

var decimal = function(dot){

if (!$(“cal_display”).value.includes(dot)) {
// Append the decimal point
$(“cal_display”).value += dot;
}

}

// function for clear all the value from display field with Clear button
var clearAll = function(){
$(“cal_display”).value = 0;
firstval = null;
secondval = null;
operator = null;
temp = null;
}

// funciton for Backspace key
var back = function(){

var newtxt=$(“cal_display”).value.slice(0, -1); // remove last digit from display field

if(newtxt==””){

$(“cal_display”).value = 0; // display 0 if no more field exist on display

}else{

$(“cal_display”).value = newtxt; // display remaining text

}

}

var changeSign = function(){

if($(“cal_display”).value.charAt(0) == “-“){

$(“cal_display”).value = $(“cal_display”).value.slice(1); // check for negative and change sign

}else{

$(“cal_display”).value = “-” + $(“cal_display”).value; // check for positive and change sign

}

}

// calculate percentage

var percent = function() {

if($(“cal_display”).value!=0){

$(“cal_display”).value = $(“cal_display”).value / 100; // calculate percentage of number on button click

}else{

$(“cal_display”).value += “.0”; // If 0 then will add .0 on button click

}

}

// calculate cos on button click

var cos = function() {

$(“cal_display”).value = Math.cos($(“cal_display”).value);
flag = true;

}

// calculate sin on button click

var sin = function() {

$(“cal_display”).value = Math.sin($(“cal_display”).value);
flag = true;

}

// calculate tan on button click

var tan = function() {

$(“cal_display”).value = Math.tan($(“cal_display”).value);
flag = true;

}

// calculate sqrt on button click

var sqrt = function() {

$(“cal_display”).value = Math.sqrt($(“cal_display”).value);
flag = true;

}

// calculate log on button click

var log = function() {

$(“cal_display”).value = Math.log($(“cal_display”).value).toFixed(8);
flag = true;

}

// calculate exponential on button click

var exp = function() {

$(“cal_display”).value = Math.exp($(“cal_display”).value).toFixed(8);
flag = true;

}

// calculate square on button click

var sqr = function() {

$(“cal_display”).value = eval($(“cal_display”).value) * eval($(“cal_display”).value);
flag = true;

}
// function to display the numberic value entered by user to perform calculation

var getvalue = function(val){

if(perenth==true){

$(“cal_display”).value += val;

}else if($(“cal_display”).value==0||flag==true){

$(“cal_display”).value = val;
flag = false;

}else{

$(“cal_display”).value += val;

}

}
// Add open parenthesis

var parenthopen = function(per){

if($(“cal_display”).value==0){

$(“cal_display”).value = per;
perenth = true;

}else if (!$(“cal_display”).value.includes(per)) {
// Append the parenthesis open point
$(“cal_display”).value += ‘*’+per;
perenth = true;

}

}

// Add close parenthesis

var parenthclose = function(per){

if ($(“cal_display”).value.includes(‘(‘) && !$(“cal_display”).value.includes(per)) {
// Append the parenthesis close point
$(“cal_display”).value += per;
perenth = false;
}

}
// show operators if parenthesis is present

var showperenths = function(oper){

if(oper==’divide’){

oper = ‘/’;

}else if(oper==’add’){

oper = ‘+’;

}else if(oper==’substract’){

oper = ‘-‘;

}else if(oper==’multiply’){

oper = ‘*’;

}else if(oper==’pi’){

oper = ‘3.14159265’;

}
//alert(oper);
getvalue(oper);

}

// calculate parenthesis values

var performperenth = function(perenths){
var str = perenths.toString();
if(str.includes(“(“)){

var arr1 = perenths.split(“(“);
var arr2 = arr1[1].split(“)”);

if(arr1[0]!=”){

return eval(arr1[0].concat(eval(arr2[0])));

}else{

return eval(arr2[0]);

}

}else{

return perenths;

}
}

// function to do the calculation on available values

var performCalculation = function(firstval, secondval, operator){

if(operator==’divide’){

temp = parseFloat(performperenth(firstval)) / parseFloat(performperenth(secondval)); //calculate division

}else if(operator==’add’){

temp = parseFloat(performperenth(firstval)) + parseFloat(performperenth(secondval)); //calculate addition

}else if(operator==’substract’){

temp = parseFloat(performperenth(firstval)) – parseFloat(performperenth(secondval)); //calculate substraction

}else if(operator==’multiply’){

temp = parseFloat(performperenth(firstval)) * parseFloat(performperenth(secondval)); //calculate multiply

}else if(operator==’pi’){

temp = parseFloat(performperenth(firstval)) * parseFloat(‘3.14159265’); //calculate pi

}else if(operator==’equal’){

temp = parseFloat(performperenth(secondval)); //show number on click of = button

}

return temp;
}
// function to get operators and check for available and remoaing value and accordingly calling perform function

var getoperator = function(oper){

if(firstval == null && oper==’pi’){

$(“cal_display”).value = “3.14159265”;
firstval = “3.14159265”;

}else if(firstval == null && oper == ‘equal’){

var result = performCalculation(”, $(“cal_display”).value, oper);
firstval = result;
secondval = null;
$(“cal_display”).value=result;

}else if(firstval == null){

firstval = $(“cal_display”).value;

}else{

secondval = $(“cal_display”).value;
var result = performCalculation(firstval, secondval, operator);
firstval = result;
secondval = null;
$(“cal_display”).value=result;
}

flag=true;
operator = oper;

}
window.onload = function() {

// get all the input fields named num in array
var buttonnum = document.getElementsByName(‘num’);
for (var i = 0, len = buttonnum.length; i < len; i++) {
buttonnum[i].onclick = function (){
getvalue (this.innerHTML);
}
}

// get all the input fields named keyoperator in array to perform various funciton
var buttonkey = document.getElementsByName(‘keyoperater’);
for (var i = 0, len = buttonkey.length; i < len; i++) {
buttonkey[i].onclick = function (){

if(perenth == true){

showperenths(this.value);

}else{

getoperator(this.value);

}
}
}

// get all the input fields named basickey in array to perform various funciton
var buttonbasic = document.getElementsByName(‘basickey’);
for (var i = 0, len = buttonbasic.length; i < len; i++) {
buttonbasic[i].onclick = function (){

if(this.value==”back”){ // check for Backspace key

back();

}else if(this.value == “clear”){ // check for clear key

clearAll();

}else if(this.value == “.”){ // check for decimal key

decimal(this.value);

}else if(this.value==”negative”){

changeSign();

}else if(this.value==”parenthopen”){

parenthopen(‘(‘);

}else if(this.value==”parenthclose”){

parenthclose(‘)’);

}

}
}

// get all the input fields named mathkey in array to perform various funciton
var buttonmath = document.getElementsByName(‘mathkey’);
for (var i = 0, len = buttonmath.length; i < len; i++) {
buttonmath[i].onclick = function (){

if(this.value==”per”){ // check for Backspace key

percent();

}else if(this.value==”cos”){ // check for cos

cos();

}else if(this.value==”sin”){ // check for sin

sin();

}else if(this.value==”tan”){ // check for tan

tan();

}else if(this.value==”sqr”){ // check for sqr

sqr();

}else if(this.value==”sqrt”){ // check for sqrt

sqrt();

}else if(this.value==”exp”){ // check for exp

exp();

}else if(this.value==”log”){ // check for exp

log();

}

}
}

};

 

Also check How to develop an Simple HTML calculator using JavaScript and CSS – Part I

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.