Simple calculator using JQuery

Simple calculator using JQuery

JavaScript is very useful when you need data interpretation and manipulation on the client side. JQuery is one of the most popular and useful JavaScript libraries. Web developers love to use JQuery and I am no different.

In this tutorial, I will demonstrate how we can create a calculator system using JQuery. This tool particularly becomes very handy for developers who build commercial or business level websites; where a small calculating tool is often required as a sidebar widget.

For creating the UI, we implement the following HTML and CSS code. The concept is simple. We create an HTML table with rows and columns to fit in the various calculator digits, operators and other options.

The full HTML and CSS code can be found here.

Check out the working demo

You might create and implement your own design. That is not an issue. Because, the main feature of the calculator is locked inside the JQuery code snippet. So, no matter what design you implement; the JQuery code must be correct for the calculator to function properly.

The JQuery code snippet is supplied below. But, before we dive into the JQuery code; I would like to discuss about the approach that I have selected.

First of all, the JQuery code is embedded within the “document.ready” method; so that the calculator is ready only after the whole document is ready loaded. This is important because the calculator might not function or malfunction if the entire HTML isn’t loaded properly.

As per our HTML structure, the table columns contain the numbers. So, we have not accessed those using ids (respective ids have not been implemented for digit boxes according to the digit value). Here, we have a point to discuss. For the DOM traversal, or in other words, for accessing each digit with the help of JQuery we could have implemented an “id” method. This method is tedious and also very bad coding technique. I have used class instead for all numbers and operators. When the same class elements are clicked, our code will differentiate the input accordingly.

Now, we already have a common class for the digits (number or operators). This is very important because; our code must keep track of the time till the user is typing numbers. As long the user is typing numbers, our first operand is being created. When the user clicks an operator, the first operand is stored and also the operator is stored. Now the code expects the second operator. At this point, if the user types numbers then it is stored as the second operand. Otherwise, the operator is overridden.

Lastly, the code also checks for wrong inputs. Suppose the user input divide by zero. These validation checks are also included.

The entire JQuery code is here.

Check out the working demo

Comments are closed.