Create a Calculator using HTML, CSS, and JavaScript


To create a calculator using HTML, CSS, and Javascript, we need to have basic understanding of working of HTML, CSS and JavaScript. Calculator is a simple tool which performs basic arithmetic calculations like Addition, Subtraction, Multiplication and Division. In this article, we are going to discuss how to create a Calculator using HTML, CSS, and JavaScript. Usually, if we observe any real-time calculator we know that it has:

  • A grid of numbers (0-9 and 00).
  • Basic arithmetic operators (+, -, /, x, %).
  • Some symbols for special operations such as (clear, backspace and equal)

The output of our Real Time Calculator will be displayed as below :

Calculator





 

Use of HTML

In this article, to create a calculator, we are using HTML to create basic structure. By using HTML, we are creating an input field, display area and buttons.

Use of CSS

We are using CSS for designing the basic structure of calculator created using HTML to make it user friendly and to make it look better. Css helps in positioning and arrangement of buttons, display area and input field in organized manner and is responsible for fonts, colors, background color, padding, margins, etc.

Use of JavaScript

In this article for creating calculator, we have used JavaScript to add functionality to each buttons, be responsive to user input. We have added click events and keyboard inputs using Javascript, so that each component can perform their respective function.

Creating a Calculator using HTML, CSS, and JS

Given below are the complete example codes of HTML, CSS and JavaScript which we have used to create calculator. It provides step-wise explaination of function they are performing.

HTML Code

This is the HTML file for our calculator. Here, we are using the HTML to create the content of the calculator UI. We are including the buttons of a calculator, input fields, display area.

In the HTML code, we have used onclick event, which means that whenever user clicks on any of the buttons then the corresponding operation is performed at the backend of the calculator using javascript.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Calculator</title>
   <link rel="stylesheet" href="style.css">
</head>
<body>
   <div id="calc">
      <div id="content">
         <form>
            <div id="output">
               <input type="text" id='res'>
            </div>
            <div class="btn">
               <input type="button" value='C' onclick="Clear()" id="clear">
               <input type="button" value='←' onclick="Back()" id="backspace">
               <input type="button" value='%' onclick="Solve('%')">
               <input type="button" value='/' onclick="Solve('/')">
               <br>
               <input type="button" value='7' onclick="Solve('7')">
               <input type="button" value='8' onclick="Solve('8')">
               <input type="button" value='9' onclick="Solve('9')">
               <input type="button" value='x' onclick="Solve('*')">
               <br>
               <input type="button" value='4' onclick="Solve('4')">
               <input type="button" value='5' onclick="Solve('5')">
               <input type="button" value='6' onclick="Solve('6')">
               <input type="button" value='-' onclick="Solve('-')">
               <br>
               <input type="button" value='1' onclick="Solve('1')">
               <input type="button" value='2' onclick="Solve('2')">
               <input type="button" value='3' onclick="Solve('3')">
               <input type="button" value='+' onclick="Solve('+')">
               <br>
               <input type="button" value='00' onclick="Solve('00')">
               <input type="button" value='0' onclick="Solve('0')">
               <input type="button" value='.' onclick="Solve('.')">
               <input type="button" value='=' onclick="Result()">
            </div>
         </form>
      </div>
   </div>
   <script src='index.js'></script>
</body>
</html>

CSS code

It is the style.css file implementing CSS for our calculator which is linked to HTML code. By this CSS code we have placed our calculator in the centre of the page using flex, gave a dark themed background to our calculator, added different color for 'c' and '←' button and resized the display input box and changed the font-size, padding of the elements.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
#calc {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}
#content {
    background: #2c302c;
    padding: 20px;
    border-radius: 10px;

}
#content form input {
    border: 0;
    outline: 0;
    width: 50px;
    height: 50px;
    border-radius: 8px;
    font-size: 15px;
    margin: 10px;
    cursor: pointer;
}
#backspace {
    background-color: rgb(237, 89, 30);
    color: white;
}
#res {
    padding: 10px;
}
#clear {
    background-color: rgb(237, 89, 30);
    color: white;
}
form #output {
    display: flex;
    justify-content: flex-end;
    margin: 15px 0;
}
form #output input {
    text-align: right;
    flex: 1;
    font-size: 25px;
}

JavaScript Code

It is the index.js file implementing Javaccript for our calculator which is linked to HTML code. This code has major functionalities like: appending values using solve function, calculating result using result function which calculates the result using 'eval' and displays an error message if there is any error in arithmetic expression, clearing the display using clear function, deleting a number using back function and at the end we have added keyboard functionalities using addEventListener.

Here is the implementation of above mentioned functions using javascript.

function Solve(val) {
   var v = document.getElementById('res');
   v.value += val;
}
function Result() {
   var num1 = document.getElementById('res').value;
   try {
      var num2 = eval(num1.replace('x', '*'));
      document.getElementById('res').value = num2;
   } catch {
      document.getElementById('res').value = 'Error';
   }
}
function Clear() {
   var inp = document.getElementById('res');
   inp.value = '';
}
function Back() {
   var ev = document.getElementById('res');
   ev.value = ev.value.slice(0, -1);
}
document.addEventListener('keydown', function (event) {
   const key = event.key;
   const validKeys = '0123456789+-*/.%';
   if (validKeys.includes(key)) {
      Solve(key === '*' ? 'x' : key);
   } else if (key === 'Enter') {
      Result();
   } else if (key === 'Backspace') {
      Back();
   } else if (key.toLowerCase() === 'c') {
      Clear();
   }
});

Updated on: 12-Jul-2024

45K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements