JavaScript Calculator Project

In this tutorial, we will learn how to create a simpleCalculatorproject in JavaScript.

We are going to use vanilla JavaScript to develop thisCalculatorproject.

JavaScript Calculator Project

Create a folder calledcalculator as project workspace, and we will create all the project files inside this folder.

1. index.html

Let's createindex.html and add the following code to it:

<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><metahttp-equiv="X-UA-Compatible"content="ie=edge"><title>Calculator</title><linkhref="style.css"rel="stylesheet"><scriptsrc="script.js"defer></script></head><body><divclass="calculator-grid"><divclass="output"><divdata-previous-operandclass="previous-operand"></div><divdata-current-operandclass="current-operand"></div></div><buttondata-all-clearclass="span-two">AC</button><buttondata-delete>DEL</button><buttondata-operation>รท</button><buttondata-number>1</button><buttondata-number>2</button><buttondata-number>3</button><buttondata-operation>*</button><buttondata-number>4</button><buttondata-number>5</button><buttondata-number>6</button><buttondata-operation>+</button><buttondata-number>7</button><buttondata-number>8</button><buttondata-number>9</button><buttondata-operation>-</button><buttondata-number>.</button><buttondata-number>0</button><buttondata-equalsclass="span-two">=</button></div></body></html>

2. script.js

Let's create a JavaScript file namedscript.js and add the following JavaScript code to it:

classCalculator{constructor(previousOperandTextElement,currentOperandTextElement){this.previousOperandTextElement=previousOperandTextElementthis.currentOperandTextElement=currentOperandTextElementthis.clear()}clear(){this.currentOperand=''this.previousOperand=''this.operation=undefined}delete(){this.currentOperand=this.currentOperand.toString().slice(0,-1)}appendNumber(number){if(number==='.'&&this.currentOperand.includes('.'))returnthis.currentOperand=this.currentOperand.toString()+number.toString()}chooseOperation(operation){if(this.currentOperand==='')returnif(this.previousOperand !==''){this.compute()}this.operation=operationthis.previousOperand=this.currentOperandthis.currentOperand=''}compute(){letcomputationconstprev=parseFloat(this.previousOperand)constcurrent=parseFloat(this.currentOperand)if(isNaN(prev)||isNaN(current))returnswitch(this.operation){case'+':computation=prev+currentbreakcase'-':computation=prev-currentbreakcase'*':computation=prev *currentbreakcase'รท':computation=prev /currentbreakdefault:return}this.currentOperand=computationthis.operation=undefinedthis.previousOperand=''}getDisplayNumber(number){conststringNumber=number.toString()constintegerDigits=parseFloat(stringNumber.split('.')[0])constdecimalDigits=stringNumber.split('.')[1]letintegerDisplayif(isNaN(integerDigits)){integerDisplay=''}else{integerDisplay=integerDigits.toLocaleString('en',{maximumFractionDigits:0})}if(decimalDigits !=null){return`${integerDisplay}.${decimalDigits}`}else{returnintegerDisplay}}updateDisplay(){this.currentOperandTextElement.innerText=this.getDisplayNumber(this.currentOperand)if(this.operation !=null){this.previousOperandTextElement.innerText=`${this.getDisplayNumber(this.previousOperand)}${this.operation}`}else{this.previousOperandTextElement.innerText=''}}}constnumberButtons=document.querySelectorAll('[data-number]')constoperationButtons=document.querySelectorAll('[data-operation]')constequalsButton=document.querySelector('[data-equals]')constdeleteButton=document.querySelector('[data-delete]')constallClearButton=document.querySelector('[data-all-clear]')constpreviousOperandTextElement=document.querySelector('[data-previous-operand]')constcurrentOperandTextElement=document.querySelector('[data-current-operand]')constcalculator=newCalculator(previousOperandTextElement,currentOperandTextElement)numberButtons.forEach(button=>{button.addEventListener('click',()=>{calculator.appendNumber(button.innerText)calculator.updateDisplay()})})operationButtons.forEach(button=>{button.addEventListener('click',()=>{calculator.chooseOperation(button.innerText)calculator.updateDisplay()})})equalsButton.addEventListener('click',button=>{calculator.compute()calculator.updateDisplay()})allClearButton.addEventListener('click',button=>{calculator.clear()calculator.updateDisplay()})deleteButton.addEventListener('click',button=>{calculator.delete()calculator.updateDisplay()})

3. style.css

Let's create a CSS file namedstyle.css and add the following CSS code to it:

*,*::before,*::after {box-sizing: border-box;font-family: Gotham Rounded, sans-serif;font-weight: normal;}body {padding:0;margin:0;background:linear-gradient(to right,#00AAFF,#00FF6C);}.calculator-grid {display: grid;justify-content: center;align-content: center;min-height:100vh;grid-template-columns:repeat(4,100px);grid-template-rows:minmax(120px, auto)repeat(5,100px);}.calculator-grid>button {cursor: pointer;font-size:2rem;border:1px solid white;outline: none;background-color:rgba(255,255,255,.75);}.calculator-grid>button:hover {background-color:rgba(255,255,255,.9);}.span-two {grid-column: span2;}.output {grid-column:1/-1;background-color:rgba(0,0,0,.75);display: flex;align-items: flex-end;justify-content: space-around;flex-direction: column;padding:10px;word-wrap: break-word;word-break: break-all;}.output .previous-operand {color:rgba(255,255,255,.75);font-size:1.5rem;}.output .current-operand {color: white;font-size:2.5rem;}

Open index.html in Browser

Let's open the index.html file in the browser, and you will be able to see the following screen:

More Free JavaScript Projects with Source Code


Comments