DONATE  
MENU
JAVASCRIPT
JSON
AJAX
HTML

JavaScript Tutorials

INTRODUCTION

» Introduction to JavaScript

» Practice IT Editor

» JavaScript Example

» JavaScript Placement

» JavaScript Syntax

» JavaScript Statements

» JavaScript Input

» JavaScript Output

» JavaScript Comments

» JavaScript Variables

» Variables' Scope

» JavaScript Operators

» JS Expressions & Concatenation

» JavaScript Data Type

» JavaScript Numbers

» Number Object

» JavaScript Strings

» String Object

» JavaScript Booleans

» Boolean Object

» JavaScript Functions

» JavaScript Arrays

» Array Object - Properties

» Array Object - Methods

» JavaScript Objects

» JavaScript Undefined

» JavaScript Nulls

CONDITIONAL TESTING

» If Statement

» If Else Statement

» JavaScript Ternary Operator

» Switch Statement

LOOPS

» For Loops

» While Loops

» Break & Continue

» For...In Loops

» do...while Loop

FUNCTIONS

» JavaScript Functions

» Creating Functions

» Functions' Parameters

» Functions' Arguments

» Function Invocation

» The Return Keyword

» The Arguments Object

» Callback Functions

» Arrow Functions

ARRAYS

» JavaScript Arrays

» Creating Arrays

» Accessing Arrays

» Looping Arrays

» Multi - dimensional Arrays

OBJECTS

» JavaScript Objects

» Creating Objects

» Prototype Definition

» Accessing Objects

» The this Keyword

AJAX

» Introduction to AJAX

JSON

» Introduction to JSON

JAVASCRIPT DATES

» The Date Object

» Date Methods

» Timing (SetInterval & SetTimeout)

MATH OBJECT

» Math Object

» Math Methods

HTML / JS DOM

» DOM Introduction

» Accessing HTML Elements in DOM

» Get And Change Elements' Contents & Values

» Change Styling - DOM CSS

» DOM Attributes

» JavaScript Event Listeners

» DOM Event Listeners

» JS Events

MISCELLANEOUS

» JS Strict Mode

» JavaScript Hoisting

» JavaScript let keyword

» Reserved Keywords

» JS Best Practices

» JavaScript vs ECMAScript

JAVASCRIPT EXAMPLES

» JavaScript Calculator

.. » JavaScript » Javascript Examples » JavaScript Calculator
Share Tweet WhatsApp

JavaScript Calculator

Now that you have learnt JavaScript, let's get to creating a beginner's application as a practical example on JavaScript. Let's create a JavaScript Calculator. You are required to study the codes and determine how all the statements were put together and the use/importance of each statement.
<!DOCTYPE html>
<html>
<head>
<title>SB Calculator</title>
<meta name='viewport' content='width=device-width; initial-scale=1'/>
</head>
<body>
<!-- SOME STYLES FOR CALC BUTTONS -->
<style>
button{
outline:none;
}
.btndata{
width:25%;
}
.btndata button{
width:100%;
border-radius:5px;
font-size:2em;
border:0;
font-weight:bold;
}
</style>
<!-- CALCULATOR BORDER -->
<div style='padding:1%; border-radius:10px; border:5px solid rgb(2,4,40);'>
<div>
<!-- DISPLAYING A NAME FOR THE CALC -->
<span style="font-weight:900;">SB Calculator</span>
<!-- THIS ELEMENT WILL ENABLE US DISPLAY TIME -->
<span id='time' style="display:inline-block; padding-left:8px; border-radius:50%; padding-right:8px; border:1px solid gray; float:right;"></span>
</div>
<!-- A TABLE TO CONTAIN CALC BUTTONS -->
<table style='width:100%; margin:auto;'>
<tbody>
<!-- A INPUT TO DISPLAY THE CALCULATOR MONITOR - WHEN USERS CLICK A BUTTON, THE INPUT IS DISPLAYED HERE -->
<tr><input id='display' style='margin-top:2%; display:block; border:1; font-size:2em; background-color:white; width:100%;' type='text' disabled/></tr>
<!-- ANSWERS WILL BE DISPLAYED HERE -->
<tr><p style="visibility:hidden; font-size:2em;" id='answer' align='right'>0</p></tr>
<!-- OFF AND ON BUTTONS -->
<tr><button id='onoff' onclick='turnOn()' style='padding:5px; font-weight:bold; width:25%; background-color:gray; border:0; text-align:center; border-radius:50%; color:white;'>ON</button></tr>
<!-- CALC BUTTONS -->
<tr class='btnrow'> 
<td class='btndata'><button class='btn' onclick='insert(this)'>+</button></td>
<td class='btndata'><button class='btn' onclick='insert(this)'>-</button></td>
<td class='btndata'><button class='btn' onclick='insert(this);'>*</button></td>
<td class='btndata'><button class='btn' onclick='insert(this);'>/</button></td>
</tr>
<tr class='btnrow'>        
<td class='btndata'><button class='btn' onclick='insert(this)'>1</button></td>
<td class='btndata'><button class='btn' onclick='insert(this)'>2</button></td>
<td class='btndata'><button class='btn' onclick='insert(this)'>3</button></td>
<td class='btndata'><button class='btn' onclick='clr()'>C</button></td>
</tr>
<tr class='btnrow'>        
<td class='btndata'><button class='btn' onclick='insert(this)'>4</button></td>
<td class='btndata'><button class='btn' onclick='insert(this)'>5</button></td>
<td class='btndata'><button class='btn' onclick='insert(this)'>6</button></td>
<td class='btndata' rowspan="4"><button class='btn' style="height:100%;" onclick='equalTo(1)'>=</button></td>
</tr>
<tr class='btnrow'>        
<td class='btndata'><button class='btn' onclick='insert(this)'>7</button></td>
<td class='btndata'><button class='btn' onclick='insert(this)'>8</button></td>
<td class='btndata'><button class='btn' onclick='insert(this)'>9</button></td>        </tr>
<tr class='btnrow'>        
<td class='btndata' rowspan="2"><button class='btn' style='background-color:red; height:100%; color:white;' onclick='del()'>DEL</button></td>
<td class='btndata'><button class='btn' onclick='insert(this)'>0</button></td>
<td class='btndata'><button class='btn' onclick='insert(this)'>00</button></td>
</tr>
<tr class='btnrow'>
<td class='btndata'><button style='font-size:1.7em;' class='btn' onclick='raiseTo()'>x<sup>2</sup></button></td>    
<td class='btndata'><button class='btn' onclick='insert(this)'>.</button></td>
</tr>
</tbody>
</table>
</div>
<script>
//THIS IS A BOOLEAN, IT ENABLES US TO KNOW THE ON/OFF STATE OF THE CALC. IF IT IS false, THE CALC IS OFF ELSE IT IS ON
var isOn = false;
    
//Invokes the getTimeNow function to display the current time
getTimeNow();
 
//Sets an interval to always invoke the getTimeNow function which is every 1 minute
setInterval(getTimeNow, 60000);
    
function getTimeNow(){
var today = new Date(); //current date object
var time = today.getHours()+" : "+today.getMinutes(); //gets current hour and concatenates with current minute
document.getElementById("time").innerText = time; //displays the time
}

//FUNCTION TO CLEAR THE CALC MONITOR OR DISPLAY - HANDLES THE CLR BUTTON
function clr(){
//checks if calculator is on before doing anything
if (isOn){
document.getElementById("display").value = ""; //Removes all values from the display element
var answer = document.getElementById("answer"); //object of the answer element
answer.value = "0"; //sets the value of the answer element to 0
answer.style.visibility = "hidden"; //hides the answer element
}
}

//TO DELETE ANY INPUT TYPED INTO THE CALCULATOR - HANDLES THE DELETE BUTTON
function del(){
//check if calculator is on before doing any thing
if (isOn)
{
var inputs = document.getElementById("display"); //object of the calculator's display or monitor
var inputStr = inputs.value; //Get the values entered into calculator - a string
if (inputStr.length > 0) //check if the length of the value is greater than zero i.e are there any actual inputs so far
{
//Below we created a new empty string and ran a loop to add the characters of the previous string except the last character
var newStr = "";
for (var i = 0; i<inputStr.length - 1; i++){
newStr += inputStr.charAt(i);
}
inputs.value = newStr; //Display the new value

equalTo(); //invokes the equalTo function to calculate the new value in the display or monitor
}
}
}

//TO INSERT VALUE - WHEN A BUTTON IS CLICKED, THIS FUNCTION INSERTS THE VALUE OF THAT BUTTON INTO THE CALCULATOR SCREEN/MONITOR
//It has parameter which will be assign the object of the button that was clicked
function insert(el){
//check if calculator is on
if (isOn){
document.getElementById("display").value += el.innerText; //inserts the innertext of the button into the calculator's monitor
equalTo(); //Calling the equalTo function to calculate the result of the new values in the display
}
}

//FUNCTION TO COMPUTE/CALCULATE USER'S INPUTS
function equalTo(clrBox){
var value = document.getElementById("display").value; //gets the values in the calculator's monitor or display
var answer = document.querySelector("#answer"); //object of the answer element
if (isOn && value != ""){//checks if calculator is on and if there are values to compute or calculate
answer.style.visibility = ""; //Makes the answer element visible
answer.innerText = eval(value); //The JS predefined eval() function enables us to evaluate the values in string and get a final answer
if (clrBox !== undefined){//clrBox is aan argument that is assigned whenever the equal to button is clicked. It enables to distinguish the equal button invocation from other invocations of this function
changeTextBox(eval(value)); //This function is invoked to clear the values in the calculator's monitor and replace with answer. This is done only when the equal to button invoked the equalTo() function
}
}
else
{
//No value in the calculator's monitor
answer.innerText = "0"; //changes answer element inner text to 0
answer.style.visibility = "hidden"; //hides the visibility of the element as well
}
}

function changeTextBox(newValue){
document.getElementById("display").value = newValue;
}

//FUNCTION TO RAISE A NUMBER TO 2 FOR THE RAISE TO POWER OF 2 (x²) BUTTON
function raiseTo(){
if (isOn){ //checks if calculator is on
var value = document.getElementById("display").value; //Gets the value of the calculator display or monitor
if (value != ""){//checks if the value is empty or not
value = Number(value); //converts the value from a string to a number
if (!Number.isNaN(value)){ //check if the new value is NAN or not
value = Math.pow(value, 2); //Raise number to 2
var answer = document.querySelector("#answer");
answer.innerText = value; //Displays the result
}
}
}
}

//FUNCTION TO TURN ON THE CALCULATOR
function turnOn(){
document.getElementById("display").setAttribute("placeholder","0"); //Changes calculator display/monitor placeholder to 0
isOn = true; //turns on the calculator
var onOffBtn = document.getElementById("onoff"); //gets the object of the on and off button
onOffBtn.style.backgroundColor = "red"; //changes its background color to red
onOffBtn.setAttribute("onclick","turnOff()"); //changes its onclick attribute to turnOff so that when users clicks on it again, it will call the turnOff function and the calc will be turned off
onOffBtn.innerText = "OFF"; //changes it innerText from ON to "OFF"
}

//FUNCTION TO TURN OFF THE CALCULATOR
function turnOff(){
var d = document.getElementById("display"); //object of the display or monitor
d.setAttribute("placeholder",""); //changes the placeholder value of the display or monitor to empty value
d.value = ""; //empties the monitor value
var answer = document.getElementById("answer"); //object of the answer element
answer.innerText = "0"; //changes the text of the answer element to 0
answer.style.visibility = "hidden"; //hides the answer element
isOn = false; //turns off the calc
var onOffBtn = document.getElementById("onoff"); //object of the on/off button
onOffBtn.style.backgroundColor = "gray"; //changes its color to gray
onOffBtn.setAttribute("onclick","turnOn()"); //changes its onclick event attribute to function turnOn. This will ensure when it is clicked again, the calculator will be turned on
onOffBtn.innerText = "ON"; //changes its text from OFF to "ON"
}
</script>
</body>
</html>

Copy PRACTICE IT

Take a short quiz on JavaScript Calculator.
Ask a question or tell us if JavaScript Calculator is easy or not.
cent?

Join our 1,090 subscribers to receive tutorials' updates!

  We won't spam your mail box. We hate it.





StackBeginner 2021 © Joseph Omamode