Today I will teach you how to create a calculator with HTML, CSS and JavaScript
HTML and CSS
<!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>Simple Calc</title>
<style>
body{
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div>
<h1>Calculator</h1>
First Number: <input type="text" name="n1" id="n1">
<br>
Second Number: <input type="text" name="n2" id="n2">
<br>
<select name="operator" id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="x">x</option>
<option value="/">/</option>
<option value="%">%</option>
</select>
<input type='button' value= 'Calculate' id="calcBtn">
<br>
<p>Answer: <span id="resultDisplay"></span></p>
</div>
<script src="script.js"></script>
</body>
</html>
JavaScript
let n1 = document.getElementById('n1');
let n2 = document.getElementById('n2');
let op = document.getElementById('operator');
let calcBtn = document.getElementById('calcBtn');
let resultDisplay = document.getElementById('resultDisplay');
calcBtn.addEventListener('click', calc);
function calc(){
if (op.value === "+"){
resultDisplay.innerHTML = (parseFloat(n1.value) + parseFloat(n2.value));
}
else if (op.value === "-"){
resultDisplay.innerHTML = (parseFloat(n1.value) - parseFloat(n2.value));
}
else if (op.value === "x"){
resultDisplay.innerHTML = (parseFloat(n1.value) * parseFloat(n2.value));
}
else if (op.value === "/"){
resultDisplay.innerHTML = (parseFloat(n1.value) / parseFloat(n2.value));
}
else{
resultDisplay.innerHTML = (parseFloat(n1.value) % parseFloat(n2.value));
}
}
If you found this blog post helpful don’t forget to check out my other projects and if you want more content follow me on
YouTube: https://www.youtube.com/channel/UC2nxqB2usQIS2c8zwVZKWEQ
Instagram: https://www.instagram.com/coding_for_the_web/
Twitter: https://twitter.com/LearnWebCoding
Comments