A simple calculator using javascript
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>JS Calculator</title> | |
</head> | |
<body> | |
<div id="calc-box"> | |
<h3 align="center">Calculator</h3> | |
<hr> | |
<table border="0" width="400"> | |
<tr> | |
<td>Enter number 1</td> | |
<td><input type="text" id="num1" value="0"></td> | |
</tr> | |
<tr> | |
<td>Enter number 2</td> | |
<td><input type="text" id="num2" value="0"></td> | |
</tr> | |
<tr> | |
<td>Result</td> | |
<td><input type="text" id="result" value="0"></td> | |
</tr> | |
</table> | |
<hr> | |
<div class="btn"> | |
<button type="button" onclick="calculate('+')">+</button> | |
<button type="button" onclick="calculate('-')">-</button> | |
<button type="button" onclick="calculate('*')">*</button> | |
<button type="button" onclick="calculate('/')">/</button> | |
<button type="button" onclick="calculate('c')">C</button> | |
</div> | |
</div> | |
<script> | |
// style the box | |
let calc_box = document.querySelector("#calc-box"); | |
calc_box.style.border = "2px solid black"; | |
calc_box.style.margin = "0 auto"; | |
calc_box.style.width = "350px"; | |
calc_box.style.padding = "5px"; | |
document.querySelector(".btn").style.textAlign = "center"; | |
let btn = document.querySelectorAll(".btn button"); | |
for (i = 0; i < btn.length; i++) { | |
btn[i].style.marginLeft = "5px"; | |
btn[i].style.height = "30px"; | |
btn[i].style.width = "30px"; | |
} | |
function calculate(operator) { | |
// declaration | |
let num1 = parseInt(document.querySelector("#num1").value); | |
let num2 = parseInt(document.querySelector("#num2").value); | |
let answer = parseInt(document.querySelector("#result").value); | |
let result = document.querySelector("#result"); | |
// calculator | |
if (operator === '+') { | |
result.value = num1 + num2; | |
} else if (operator === '-') { | |
result.value = num1 - num2; | |
} else if (operator === '*') { | |
result.value = num1 * num2; | |
} else if (operator === '/') { | |
result.value = num1 / num2; | |
} else if (operator === 'c') { | |
result.value = answer * 0;; | |
document.querySelector("#num1").value = num1 * 0; | |
document.querySelector("#num2").value = num2 * 0; | |
} else { | |
alert("Invalid operator"); | |
} | |
// change the color to red if negative | |
if (result.value < 0) { | |
result.style.color = "red"; | |
} else { | |
result.style.color = "black"; | |
} | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment