In this tutorial, I will tell you two ways to make a calculator using basic HTML, CSS and JavaScript. In first way we make functions for all operations and in the second we use some inbuilt global function to make a calculator. In both cases we are going to add some simple math operations like addition, subtraction, multiplication, division in our basic calculator. This project will help you to improve your logical ability and coding skills.
JavaScript Calculator Example
Method 1:
Mainly the functions that we need to work for calculator are handling the keypresses, inputting the digits, inputting the decimal point/key, handling operators, resisting the calculators, updating the display, equal key and clear key.
As we know calculator consists of keys and display. So, in the UI perspective we have to work on:
calculator tile – where we show the title
input buttons – where we display all keys
output screen – This is the screen where we can check what input we are entering and showing all the values that we entered.
Before starting this Project you must have knowledge or idea of these things:
- if-else statements
- javascript functions
- arrow function
- some operators like && and ||
- change the text with the value attribute
- add event listeners
- querySelector
- string methods like includes, contains etc.
- eval function
So, coding part begins here for the first case. Initially, we have to make a div container in which we are going to add all buttons with proper styling. To make this UI we use CSS Grid box which is the best practice of writing proper responsive code. After this, we start work on functionalities.
Firstly we have to initialise the value of each variable and constant. Then we check what key is pressed by the user like operators, operands, decimal or clear according to this key we store it in different variables that we declared. So, when the user hits number keys then we store these values in operands. We define the separate function for each operation like inputting the digit, updating the display, decimal enter etc.
You can check the whole code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <style> html { font-size: 62.5%; box-sizing: border-box; } *, *::before, *::after { margin: 0; padding: 0; box-sizing: inherit; } .calculator { border: 1px solid #ccc; border-radius: 5px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 400px; } .output-screen { width: 100%; font-size: 5rem; height: 80px; border: none; background-color: gray; color: #fff; text-align: right; padding-right: 20px; padding-left: 10px; } button { height: 60px; background-color: #fff; border-radius: 3px; border: 1px solid #c4c4c4; background-color: transparent; font-size: 2rem; color: #333; background-image: linear-gradient(to bottom,transparent,transparent 50%,rgba(0,0,0,.04)); box-shadow: inset 0 0 0 1px rgba(255,255,255,.05), inset 0 1px 0 0 rgba(255,255,255,.45), inset 0 -1px 0 0 rgba(255,255,255,.15), 0 1px 0 0 rgba(255,255,255,.15); text-shadow: 0 1px rgba(255,255,255,.4); } button:hover { background-color: #eaeaea; } .operator { color: #337cac; } .clear-value { background-color: green; border-color: #b0353a; color: #fff; } .clear-value:hover { background-color: #f17377; } .calculate-value { background-color: blue; border-color: #337cac; color: #fff; height: 100%; grid-area: 2 / 4 / 6 / 5; } .calculate-value:hover { background-color: #4e9ed4; } .display-keys { display: grid; grid-template-columns: repeat(4, 1fr); grid-gap: 20px; padding: 20px; } </style> <body> <div class="calculator"> <h1 style="text-align: center;">Simple Javascript calculator</h1> <input type="text" class="output-screen" value="" disabled /> <div class="display-keys"> <button class="operator" value="+">+</button> <button class="operator" value="-">-</button> <button class="operator" value="*">×</button> <button class="operator" value="/">÷</button> <button value="7">7</button> <button value="8">8</button> <button value="9">9</button> <button value="4">4</button> <button value="5">5</button> <button value="6">6</button> <button value="1">1</button> <button value="2">2</button> <button value="3">3</button> <button value="0">0</button> <button class="decimal" value=".">.</button> <button class="clear-value" value="clear-value">AC</button> <button class="calculate-value operator" value="=">=</button> </div> </div> </body> <script> const calculator = { outputValue: '0', firstValue: null, flagForSecondOperand: false, operator: null, }; function inputDigit(digit) { const { outputValue, flagForSecondOperand } = calculator; if (flagForSecondOperand === true) { calculator.outputValue = digit; calculator.flagForSecondOperand = false; } else { calculator.outputValue = outputValue === '0' ? digit : outputValue + digit; } } function inputDecimal(dot) { if (calculator.flagForSecondOperand === true) return; // If the `outputValue` does not contain a decimal point if (!calculator.outputValue.includes(dot)) { // Append the decimal point calculator.outputValue += dot; } } function handleOperator(nextOperator) { const { firstValue, outputValue, operator } = calculator const inputValue = parseFloat(outputValue); if (operator && calculator.flagForSecondOperand) { calculator.operator = nextOperator; return; } if (firstValue == null) { calculator.firstValue = inputValue; } else if (operator) { const currentValue = firstValue || 0; const result = performCalculation[operator](currentValue, inputValue); calculator.outputValue = String(result); calculator.firstValue = result; } calculator.flagForSecondOperand = true; calculator.operator = nextOperator; } const performCalculation = { '/': (firstValue, secondOperand) => (firstValue / secondOperand).toFixed(5), '*': (firstValue, secondOperand) => firstValue * secondOperand, '+': (firstValue, secondOperand) => firstValue + secondOperand, '-': (firstValue, secondOperand) => firstValue - secondOperand, '=': (firstValue, secondOperand) => secondOperand }; function resetCalculator() { calculator.outputValue = '0'; calculator.firstValue = null; calculator.flagForSecondOperand = false; calculator.operator = null; } function updateDisplay() { const display = document.querySelector('.output-screen'); display.value = calculator.outputValue; } updateDisplay(); const keys = document.querySelector('.display-keys'); keys.addEventListener('click', (event) => { const { target } = event; if (!target.matches('button')) { return; } if (target.classList.contains('operator')) { handleOperator(target.value); updateDisplay(); return; } if (target.classList.contains('decimal')) { inputDecimal(target.value); updateDisplay(); return; } if (target.classList.contains('clear-value')) { resetCalculator(); updateDisplay(); return; } inputDigit(target.value); updateDisplay(); }); </script> </html> |
Method 2:
We can also make a JavaScript calculator using the eval function. This function is used to evaluate any string. This is a built-in function of JS.
Here we used the table tag to make UI and for adding additional functions we use form HTML element. On each keypress, we put on click method to add that value to the output screen. And after this eval function evaluate all values when you click on any operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<form name="calculator"> <table> <tr> <td colspan="4"> <input type="text" name="display" id="display" disabled> </td> </tr> <tr> <td><input type="button" name="one" value="1" onclick="calculator.display.value += '1'"></td> <td><input type="button" name="two" value="2" onclick="calculator.display.value += '2'"></td> <td><input type="button" name="three" value="3" onclick="calculator.display.value += '3'"></td> <td><input type="button" class="operator" name="plus" value="+" onclick="calculator.display.value += '+'"></td> </tr> <tr> <td><input type="button" name="four" value="4" onclick="calculator.display.value += '4'"></td> <td><input type="button" name="five" value="5" onclick="calculator.display.value += '5'"></td> <td><input type="button" name="six" value="6" onclick="calculator.display.value += '6'"></td> <td><input type="button" class="operator" name="minus" value="-" onclick="calculator.display.value += '-'"></td> </tr> <tr> <td><input type="button" name="seven" value="7" onclick="calculator.display.value += '7'"></td> <td><input type="button" name="eight" value="8" onclick="calculator.display.value += '8'"></td> <td><input type="button" name="nine" value="9" onclick="calculator.display.value += '9'"></td> <td><input type="button" class="operator" name="times" value="x" onclick="calculator.display.value += '*'"></td> </tr> <tr> <td><input type="button" name="zero" value="0" onclick="calculator.display.value += '0'"></td> <td><input type="button" name="doit" value="=" onclick="calculator.display.value = eval(calculator.display.value)"></td> <td><input type="button" class="operator" name="div" value="." onclick="calculator.display.value += '.'"></td> <td><input type="button" class="operator" name="div" value="/" onclick="calculator.display.value += '/'"></td> </tr> </table> <input type="button" id="clear" name="clear" value="clear" style="width:12%" onclick="calculator.display.value = ''"> </form> |
Comment down below if you have any queries related to javascript calculator.