HTML code
<title>Calculator</title>CSS code
- { margin: 0; padding: 0; box-sizing: border-box; } #calc { width: 100%; height: 100vh; display: flex; justify-content: center; align-items: center; } #content { background: #2c302c; padding: 20px; border-radius: 10px;
} #content form input { border: 0; outline: 0; width: 50px; height: 50px; border-radius: 8px; font-size: 15px; margin: 10px; cursor: pointer; } #backspace { background-color: rgb(237, 89, 30); color: white; } #res { padding: 10px; } #clear { background-color: rgb(237, 89, 30); color: white; } form #output { display: flex; justify-content: flex-end; margin: 15px 0; } form #output input { text-align: right; flex: 1; font-size: 25px; }
JS code
function Solve(val) { var v = document.getElementById('res'); v.value += val; } function Result() { var num1 = document.getElementById('res').value; try { var num2 = eval(num1.replace('x', '')); document.getElementById('res').value = num2; } catch { document.getElementById('res').value = 'Error'; } } function Clear() { var inp = document.getElementById('res'); inp.value = ''; } function Back() { var ev = document.getElementById('res'); ev.value = ev.value.slice(0, -1); } document.addEventListener('keydown', function (event) { const key = event.key; const validKeys = '0123456789+-/.%'; if (validKeys.includes(key)) { Solve(key === '*' ? 'x' : key); } else if (key === 'Enter') { Result(); } else if (key === 'Backspace') { Back(); } else if (key.toLowerCase() === 'c') { Clear(); } });