Calculator help you to solve a arithmetic operations. And Today you are going to learn about building a simple calculator using a JavaScript.
index.html file :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Project</title>
</head>
<body>
<div class="container">
<h1>Calculator</h1>
<div class="calculator">
<input type="text" name="display" id="display">
<table>
<tr>
<td><button>(</button></td>
<td><button>)</button></td>
<td><button>AC</button></td>
<td><button>%</button></td>
</tr>
<tr>
<td><button>7</button></td>
<td><button>8</button></td>
<td><button>9</button></td>
<td><button>X</button></td>
</tr>
<tr>
<td><button>4</button></td>
<td><button>5</button></td>
<td><button>6</button></td>
<td><button>-</button></td>
</tr>
<tr>
<td><button>1</button></td>
<td><button>2</button></td>
<td><button>3</button></td>
<td><button>+</button></td>
</tr>
<tr>
<td><button>0</button></td>
<td><button>.</button></td>
<td><button>/</button></td>
<td><button>=</button></td>
</tr>
</table>
</div>
</div>
<script src="calc.js"></script>
</body>
</html>
For the styling part , create a style.css file with the following code :
.container{
text-align: center;
margin-top: 30px;
}
table{
margin: auto;
}
input{
border-radius: 21px;
border: 5px solid coral;
font-size: 34px;
height: 65px;
width: 456px;
}
button{
border-radius: 10px;
font-size: 40px;
width: 102px;
height: 90px;
margin: 6px;
background-color: coral;
}
.calculator{
border: 8px solid crimson;
background-color: greenyellow;
padding: 23px;
border-radius: 10px;
display: inline-block;
}
After styling your css, you will see like the below diagram:
Now the main part for the functionality is done using the JavaScript language.
let display = document.getElementById('display');
buttons = document.querySelectorAll('button');
let displayValue = '';
for(item of buttons){
item.addEventListener('click',(e)=>{
buttonText = e.target.innerText;
console.log('Button text is ',buttonText);
if(buttonText== 'X'){
buttonText = '*';
displayValue += buttonText;
displayValue = displayValue;
}
else if(buttonText =='AC'){
displayValue = "";
display.value = displayValue;
}
else if(buttonText =='='){
display.value = eval(displayValue);
}
else{
displayValue += buttonText;
display.value = displayValue
}
})
}
Download the code from GitHub and full tutorial is uploaded on YouTube
If you have any query related to this article please do comment below :
Comments are closed.