write a code for simple calculator in html 5
Sure, here’s a simple calculator implemented using HTML5:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
}
.calculator {
width: 200px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f9f9f9;
}
input[type="text"] {
width: 100%;
margin-bottom: 10px;
padding: 5px;
font-size: 18px;
}
input[type="button"] {
width: 48%;
padding: 10px;
margin: 5px;
font-size: 16px;
border: none;
cursor: pointer;
background-color: #007bff;
color: #fff;
border-radius: 5px;
}
input[type="button"]:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="calculator">
<input type="text" id="display" readonly>
<div>
<input type="button" value="7" onclick="addToDisplay('7')">
<input type="button" value="8" onclick="addToDisplay('8')">
<input type="button" value="9" onclick="addToDisplay('9')">
<input type="button" value="+" onclick="addToDisplay('+')">
</div>
<div>
<input type="button" value="4" onclick="addToDisplay('4')">
<input type="button" value="5" onclick="addToDisplay('5')">
<input type="button" value="6" onclick="addToDisplay('6')">
<input type="button" value="-" onclick="addToDisplay('-')">
</div>
<div>
<input type="button" value="1" onclick="addToDisplay('1')">
<input type="button" value="2" onclick="addToDisplay('2')">
<input type="button" value="3" onclick="addToDisplay('3')">
<input type="button" value="*" onclick="addToDisplay('*')">
</div>
<div>
<input type="button" value="0" onclick="addToDisplay('0')">
<input type="button" value="." onclick="addToDisplay('.')">
<input type="button" value="=" onclick="calculate()">
<input type="button" value="/" onclick="addToDisplay('/')">
</div>
<div>
<input type="button" value="C" onclick="clearDisplay()">
</div>
</div>
<script>
function addToDisplay(value) {
document.getElementById("display").value += value;
}
function calculate() {
try {
document.getElementById("display").value = eval(document.getElementById("display").value);
} catch (error) {
document.getElementById("display").value = 'Error';
}
}
function clearDisplay() {
document.getElementById("display").value = '';
}
</script>
</body>
</html>
This HTML code creates a simple calculator with buttons for numbers (0-9), arithmetic operations (+, -, *, /), decimal point (.), equals (=), and clear (C). The JavaScript functions addToDisplay
, calculate
, and clearDisplay
handle the calculator’s functionality.