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

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

In this article we will build Simple Calculator with all functionalities as shown on pic using JavaScript and html and CSS for styling.

For the ease of understanding we are dividing this into two parts. In first part we will learn how to create structure for calculator and add some styles to give our calculator nice look.

In second part we will add the functionality for each button and calculation like log, sin, cos, tan and pi etc with basic functionalities of addition, subtraction, multiplication and division.

Building the Calculator

In various website you will find the use of form to display and calculate the various functions, however here we will use buttons without use of form element. We will check the onclick event of button and call the required function.

Lets build the html of our calculator. To build same we need one input filed to display the user entry and result of calculation. This will be our display area. As per our pic you can find we have different color buttons. We have separated our buttons into 4 sections.

1) Number keys with button name “num“,
2) basic keys with name “basickey” these are keys with basic signs like backspace, clear, parenthesis, decimal value etc.
3) key operators with name “keyoperator” for addition, subtraction, multiplication and division.
4) math keys with name “mathkey” to calculate sin, cos, tan etc.

To start with create a div with id “calculator”. Please note you can change the variables and id of JavaScript and html as per yours requirement. After creation of div add one input field with id “cal_display” like below.

If implemented properly your calculator design should look similar to the image or if you have changed the css then color could be different. however basic structure will be same.

Now we need to add the functionality of all buttons. Here if user click on any number key then it should be visible on our input field called “cal_display”. Once user click on the addition, subtraction, division, or multiplication button system should remember the input value and function clicked to perform the calculation and display the next value. Try to add this basic function yourself first and see how good you can do with the same. In our comment section you can write your feedback or requirement if you would like to add some other functionality in your calculator. We will try to give answer on the same asap.

In next part we will show you how to complete the calculator after adding JavaScript file and create different functions to calculate different values as per BOD-MAS formula if user add parenthesis to calculate.