Pull to refresh

Creating a calculator using Jquery — My Project

In this article, we are going to build a simple calculator which enables a user to do basic calculations like addition, subtraction, multiplication, and division. Readers are expected to have a firm grasp on the fundamentals of Javascript and jQuery as we will be using them a lot in this project. This project will help you to combine everything you have learned so far. We will be making an on-screen calculator using HTML, CSS, and jQuery right from the scratch. We will walk you through the various steps you can take, but again, how you implement them is really up to you.

Target Website:-

Getting started:-

We start off by creating a folder named jQuery Project. We open this folder in an editor. I am using Atom for it. Having done that, we will create a file named ‘index.html’ which will be storing the Html structure of our web page.

Creating index.html file:-

We give our web page the title “My calculator”. We will be using Orbitron font so we need to include this font in our project. We use googleapis for it and link it to our project with the following code:-

<link href="https://fonts.googleapis.com/css?family=Orbitron " rel="stylesheet">

We also include jQuery in our project with the following code:-

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

Inside the body tag, we declare a div element that will be containing our calculator. For the display panel of the calculator, we wrap it in a form tag and include an input tag in it which will be storing our calculated value. This can be achieved with the following lines of code:-

<form name="form">
	<input class="inputDisplay">
</form>

After this, we include buttons for the operators and the operands, and some other functional buttons. For each button, we associate them with an onclick( ) function which gets called whenever they are clicked. This can be achieved with the following piece of code:-

<table>
	<tr>
		<td><input type="button" value="C" onclick="clearInput()" style = "background-color: red"></td>
		<td><input type="button" value="<" onclick="deleteCharacter()"></td>
		<td><input type="button" value="/" onclick="insertCharacter('/')"></td>
		<td><input type="button" value="x" onclick="insertCharacter('*')"></td>
	</tr>
	<tr>
		<td><input type="button" value="7" onclick="insertCharacter(7)"></td>
		<td><input type="button" value="8" onclick="insertCharacter(8)"></td>
		<td><input type="button" value="9" onclick="insertCharacter(9)"></td>
		<td><input type="button" value="-" onclick="insertCharacter('-')"></td>
</tr>
	<tr>
		<td><input type="button" value="4" onclick="insertCharacter(4)"></td>
		<td><input type="button" value="5" onclick="insertCharacter(5)"></td>
		<td><input type="button" value="6" onclick="insertCharacter(6)"></td>
		<td><input type="button" value="+" onclick="insertCharacter('+')"></td>
	</tr>
	<tr>
		<td><input type="button" value="1" onclick="insertCharacter(1)"></td>
		<td><input type="button" value="2" onclick="insertCharacter(2)"></td>
		<td><input type="button" value="3" onclick="insertCharacter(3)"></td>
		<td rowspan=2><input type="button" value="=" onclick="result()"  style="height: 158px; background-color: green"></td>
	</tr>
	<tr>
		<td colspan="2"><input type="button" value="0" onclick="insertCharacter(0)" style="width: 158px; ;"></td>
		<td><input type="button" value="." onclick="insertCharacter('.')"></td>
	</tr>
	</table>

Observation:-

We see an unstyled version of the calculator with simple buttons. No functionalities have been added yet and nothing happens when we click on them.

Output:-

Styling our web page:-

As the next steps, we add styling to our buttons and the display panel. For this, we link a stylesheet to our index.html. We add CSS properties to the classes which we have associated with the buttons. For each element we give them a styling with the following lines of code:-

* {
	margin: 0;
	padding: 0;
	font-size: 35px;
	font-family: 'Orbitron' , sans-serif ;
}

Observation:-

After this, we style the container div element by giving it a background color, aligning it to the center, giving it some padding, and adding some border-radius to it. This can be achieved by the following lines of code:-

.calculator {
	width: 344px;
	margin: auto;
	background-color: #39383d;
	padding: 20px;
	border-radius: 8px;
}

Observation:-

After this, we style the display panel of our calculator. We give it a dirty greenish background color and some margin at the bottom with some border-radius. This can be achieved with the following lines of code:-

.inputDisplay {
	width: 100%;
	height: 80px;
	background-color: #a2af77;
	margin-bottom: 20px;
	border-radius:10px;
}

Observation:-

After that, we style all the buttons in our calculator. We set the color of the text as white and give the background color a greyish color. We give a small margin to each of the buttons and add some border-radius to each of the buttons. This can be achieved with the following lines of code:-

input[type=button] {
	width: 80px;
	height: 80px;
	margin: 3px;
	color: #fff;
	border-radius: 8px;
	background-color: #58595b
}

Observation:-

The web page now looks pretty much good. We now need to add functionalities to the buttons.

Adding Functionalities:-

We link our index.html to a javascript file named “functionalities.js”. Here we use jQuery to define the functions which get called when any buttons are clicked on the web page. We define the function ‘deleteCharacter’ which should remove the last inputted character from the display panel. This can be achieved with the following lines of code:-

function deleteCharacter() {
	let currentValue = $('.inputDisplay').val();
	$('.inputDisplay').val(currentValue.substring(0, currentValue.length - 1));
}

Here, we first select the value which is currently being shown in the display panel. We then take a substring of the current display value having a length of one less than the original string value.

We then define the function ‘insertCharacter’ which should insert a new character in our display panel. This can be achieved with the following lines of code:-

function insertCharacter(char) {
	let currentValue = $('.inputDisplay').val();
	let length = currentValue.length;
	let flag = false;
	if(char == '+' || char == '-' || char == '*' || char == '/')
	flag = true;
	if(length == 0)
	{
		if(flag)
		return;
	}
	let flagNew = false;
	let lastCharacter = currentValue[length-1];
	if(lastCharacter == '+' || lastCharacter == '-' || lastCharacter == '*' || lastCharacter == '/')
	flagNew = true;
	if(flag && flagNew)
	$('.inputDisplay').val(currentValue.substring(0,length-1) + char);
	else
	$('.inputDisplay').val($('.inputDisplay').val() + char);
}

Here, we first check if the new character to be inserted is an operator. We store the result in a variable ‘flag’. We now check that if the length of the display panel content is 0 and if so, we simply return. This is because we are trying to add an operator without having any operand. We now check if the last character of the display panel is an operator or an operand. If it is an operator and we are trying to insert a new operator we simply replace the previous one. Else, we simply insert the character at the end. For doing so we use the $(“className”).val( ) function.

Next, we define the function ‘clearInput’ which should clear our display panel. The following lines of code implement it:-

function clearInput() {
	$('.inputDisplay').val('');
}

Here, we simply select our display panel element by its class name and set its value to “” using the val function of jQuery.

Next, we define the function ‘result’ which evaluates the expression in the display panel and shows the result. For achieving this, we use the eval( ) function, an inbuilt function in jQuery to evaluate any arithmetic expression. The following lines of code implement it:-

function result() {
	let currentValue = $('.inputDisplay').val();
	let length = currentValue.length;
	let flag = false;
	let char = currentValue[length-1];
	if(char == '+' || char == '-' || char == '*' || char == '/')
	flag = true;
	if(flag)
		$('.inputDisplay').val("ERROR!");
	else
		$('.inputDisplay').val(eval($('.inputDisplay').val()));
}

Here, we first get hold of the display panel value in the variable ‘currentValue’ using the val( ) function of jQuery. We check if the last character is an operator, it implies that the expression is invalid and we present ERROR! in the display panel. If not so, we evaluate the expression using the eval( ) function and present it on the screen.

The final webpage:-

Some play around with the web page:-

Input:-

Output:-

Input:-

Output:-

Input:-

Output:-

Source code:-

index.html :-

<!DOCTYPE html>
<html>
<head>
	<title>My calculator</title>
	<link href="https://fonts.googleapis.com/css?family=Orbitron " rel="stylesheet">
	<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
	<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
	<div class="calculator">
		<form name="form">
			<input class="inputDisplay">
		</form>
		<table>
			<tr>
				<td><input type="button" value="C" onclick="clearInput()" style = "background-color: red"></td>
				<td><input type="button" value="<" onclick="deleteCharacter()"></td>
				<td><input type="button" value="/" onclick="insertCharacter('/')"></td>
				<td><input type="button" value="x" onclick="insertCharacter('*')"></td>
			</tr>
			<tr>
				<td><input type="button" value="7" onclick="insertCharacter(7)"></td>
				<td><input type="button" value="8" onclick="insertCharacter(8)"></td>
				<td><input type="button" value="9" onclick="insertCharacter(9)"></td>
				<td><input type="button" value="-" onclick="insertCharacter('-')"></td>
			</tr>
			<tr>
				<td><input type="button" value="4" onclick="insertCharacter(4)"></td>
				<td><input type="button" value="5" onclick="insertCharacter(5)"></td>
				<td><input type="button" value="6" onclick="insertCharacter(6)"></td>
				<td><input type="button" value="+" onclick="insertCharacter('+')"></td>
			</tr>
			<tr>
				<td><input type="button" value="1" onclick="insertCharacter(1)"></td>
				<td><input type="button" value="2" onclick="insertCharacter(2)"></td>
				<td><input type="button" value="3" onclick="insertCharacter(3)"></td>
				<td rowspan=2><input type="button" value="=" onclick="result()"  style="height: 158px; background-color: green"></td>
			</tr>
			<tr>
				<td colspan="2"><input type="button" value="0" onclick="insertCharacter(0)" style="width: 158px; ;"></td>
				<td><input type="button" value="." onclick="insertCharacter('.')"></td>
			</tr>
		</table>
	</div>
	<script type="text/javascript" src="functionalities.js"></script>
</body>
</html>

styles.css :-

* {
	margin: 0;
	padding: 0;
	font-size: 35px;
	font-family: 'Orbitron' , sans-serif ;
}
.calculator {
	width: 344px;
	margin: auto;
	background-color: #39383d;
	padding: 20px;
	border-radius: 8px;
}

.inputDisplay {
	width: 100%;
	height: 80px;
	background-color: #a2af77;
	margin-bottom: 20px;
	border-radius:10px;
}

input[type=button] {
	width: 80px;
	height: 80px;
	margin: 3px;
	color: #fff;
	border-radius: 8px;
	background-color: #58595b
} 

functionalities.js :-

function deleteCharacter() {
	let currentValue = $('.inputDisplay').val();
	$('.inputDisplay').val(currentValue.substring(0, currentValue.length - 1));
}
function insertCharacter(char) {
	let currentValue = $('.inputDisplay').val();
	let length = currentValue.length;
	let flag = false;
	if(char == '+' || char == '-' || char == '*' || char == '/')
	flag = true;
	if(length == 0)
	{
		if(flag)
		return;
	}
	let flagNew = false;
	let lastCharacter = currentValue[length-1];
	if(lastCharacter == '+' || lastCharacter == '-' || lastCharacter == '*' || lastCharacter == '/')
	flagNew = true;
	if(flag && flagNew)
	$('.inputDisplay').val(currentValue.substring(0,length-1) + char);
	else
	$('.inputDisplay').val($('.inputDisplay').val() + char);
}
function clearInput() {
	$('.inputDisplay').val('');
}
function result() {
	let currentValue = $('.inputDisplay').val();
	let length = currentValue.length;
	let flag = false;
	let char = currentValue[length-1];
	if(char == '+' || char == '-' || char == '*' || char == '/')
	flag = true;
	if(flag)
		$('.inputDisplay').val("ERROR!");
	else
		$('.inputDisplay').val(eval($('.inputDisplay').val()));
}

Conclusion:-

After going through this project, readers will become more confident in applying jQuery to their project. This project is to get readers started on using jQuery. Practice leads to perfection. One should start implementing jQuery in their projects to have a better understanding of it. jQuery is an important topic for interviews as well and one should be well versed with the fundamentals of it. To go through some of the top interview questions on jQuery, one can visit this Link.

Some useful tips:-

1) If you are using ready( ) function, you can always use the shortcut method.

Example:-

$(document).ready(function (){
		// your code
	});
This can be written as :-
$(function (){
		// your code
	});

2) Compress your jQuery scripts. A big project implies a lot of usage of jQuery plugins and one should compress all of their jQuery so that it does not slow down the web page.

3) Try to give context for your selectors. If you use a selector, DOM needs to traverse the entire web page which could be very expensive. Providing context as a second parameter could really speed up.

Example:-

$ ( “#id1” ) would select the element having “id1” as its id attribute. However, if the elements are listed together in a container with a specific class name we can write the above statement as $ ( “#id1”, “.className” ). This would make the selection process a lot faster.

Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.