<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-Time Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f4f4f4;
padding: 20px;
}
.calculator {
width: 300px;
margin: auto;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
}
input {
width: 90%;
padding: 10px;
margin-bottom: 10px;
font-size: 18px;
text-align: right;
border: 1px solid #ccc;
border-radius: 5px;
}
.result {
font-size: 24px;
font-weight: bold;
color: #333;
}
</style>
</head>
<body>
<h2>Real-Time Calculator</h2>
<div class="calculator">
<input type="text" id="expression" placeholder="Type here..." oninput="calculate()">
<div class="result" id="result">= 0</div>
</div>
<script>
function calculate() {
let input = document.getElementById("expression").value;
let resultBox = document.getElementById("result");
try {
if (input.trim() === "") {
resultBox.innerText = "= 0";
return;
}
// Validate input: allow numbers, operators, parentheses, and decimals
if (!/^[-+*/()\d.\s]+$/.test(input)) {
throw new Error("Invalid characters");
}
// Insert implicit multiplication (e.g., 2(3) -> 2*(3), (2)(3) -> (2)*(3)
input = input.replace(/(\d)\(/g, '$1*(').replace(/\)(\d)/g, ')*$1').replace(/\)\(/g, ')*(');
// Evaluate expression safely
let result = new Function('return ' + input)();
resultBox.innerText = "= " + result;
} catch (error) {
resultBox.innerText = "= Error";
}
}
</script>
</body>
</html>
Multiply = *
Divide = /