Home / CSS / Create simple calculator using javascript

Create simple calculator using javascript

Create a simple calculator using javascript

In this tutorial you will learn how to create a simple calculator using javascript. Which can evaluate a simple arithmetic operation on integers values . The Calculator has two main parts Result section and key section. There are several keys based on span element. There is a  event listener whenever a button is clicked it takes it HTML (innerHTML) value and concat it with the string value of the result section. Whenever a user clicks on the evaluate button the built in function of javascript evaluate the mathematical expression inside the screen section.

Step 1 (HTML):

Here we have divided our calculator into two main parts Result and Key. The result block shows the number being clicked and the answer of the mathematical expression after evaluation. The key sections contains the buttons for the calculator


HTML only preview of calculator

So this is the preview of the html only page let us add some css.

Step 2: (CSS)

I am not going to explain the whole css however, i will tell you the few points that are mandatory to make your calculator looks well. In #calculator #key span.button i set the display property to inline-block; This is because we cannot apply width and height to the span element so we have to set it to the display: inline-block; so that we can apply height and width on it.

Step 3: (Javascript)

In javascript we are selecting our result area and we are targeting all the span elements which has class button and result variable that holds the value for mathematical expression. Then we are iterating through all the elements and adding an event listener on each element does this do whenever a button is click it checks it innerHTML if it is  a ‘=’ sign then we will evaluate the mathematical expression stored in result variable (eval() is a built-in javascript function used to evaluate mathematical string expressions) else if the innerHTML is ‘C’ then we are going to clear the screen and if above two conditions are not true then definitely we are going to execute the else part in else part we are concating the button click innerHTML with the value already stored in the result variable.


Final Code:


Javascript Simple Calculator Preview

Download Now View Demo

Share This:

About Hasnain

Check Also


CSS Buttons: Slide up text on hover

You’d never go on a hike without a compass or a map. No one has …