Calculator Source code | HTML CSS JAVASCRIPT
This code creates a simple calculator with HTML, CSS, and JavaScript. You can further enhance it by adding more functionalities or styles as per your requirements.
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calculator">
<input type="text" id="display" readonly>
<div class="keys">
<button onclick="appendNumber('7')">7</button>
<button onclick="appendNumber('8')">8</button>
<button onclick="appendNumber('9')">9</button>
<button onclick="appendOperator('+')">+</button>
<button onclick="appendNumber('4')">4</button>
<button onclick="appendNumber('5')">5</button>
<button onclick="appendNumber('6')">6</button>
<button onclick="appendOperator('-')">-</button>
<button onclick="appendNumber('1')">1</button>
<button onclick="appendNumber('2')">2</button>
<button onclick="appendNumber('3')">3</button>
<button onclick="appendOperator('*')">*</button>
<button onclick="appendNumber('0')">0</button>
<button onclick="appendNumber('.')">.</button>
<button onclick="clearDisplay()">C</button>
<button onclick="calculate()">=</button>
<button onclick="appendOperator('/')">/</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
css:
body {
font-family: Arial, sans-serif;
}
.calculator {
max-width: 300px;
margin: 0 auto;
text-align: center;
padding: 20px;
background-color: #f2f2f2;
border-radius: 10px;
}
#display {
width: 100%;
margin-bottom: 10px;
padding: 10px;
font-size: 1.5em;
}
.keys {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 5px;
}
button {
padding: 10px;
font-size: 1.2em;
border: none;
background-color: #4CAF50;
color: white;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background-color: #45a049;
}
js
let expression = '';
function appendNumber(num) {
expression += num;
document.getElementById('display').value = expression;
}
function appendOperator(operator) {
expression += operator;
document.getElementById('display').value = expression;
}
function clearDisplay() {
expression = '';
document.getElementById('display').value = '';
}
function calculate() {
try {
const result = eval(expression);
document.getElementById('display').value = result;
expression = '';
} catch (error) {
document.getElementById('display').value = 'Error';
}
}
No comments: