WEBLEB
Home
Editor
Login
Pro
English
English
Français
Español
Português
Deutsch
Italiano
हिंदी
Simple Calculator
1128
Andev.web
Open In Editor
Publish Your Code
Recommended
17 May 2024
Simple login form
2 March 2023
Simple Login Form
13 April 2024
Simple CSS Card Template
HTML
Copy
Andev Web
AC
DEL
%
/
7
8
9
*
4
5
6
-
1
2
3
+
0
00
.
=
CSS
Copy
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap"); * { margin: 0; padding: 0; box-sizing: border-box; font-family: "Poppins", sans-serif; } body { height: 100vh; display: flex; align-items: center; justify-content: center; background: #e0e3eb; } .container { position: relative; max-width: 300px; width: 100%; border-radius: 12px; padding: 10px 20px 20px; background: #fff; box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05); } .display { height: 80px; width: 100%; outline: none; border: none; text-align: right; margin-bottom: 10px; font-size: 25px; color: #000e1a; background-color: #f1f1f1; pointer-events: none; caret-color: transparent; border-radius: 10px; padding: 15px 20px; } .buttons { display: grid; grid-gap: 10px; grid-template-columns: repeat(4, 1fr); } .buttons button { padding: 10px; border-radius: 6px; border: none; font-size: 20px; cursor: pointer; background-color: #eee; transition: background-color 0.3s ease; } .buttons button:hover { background-color: #d3d3d3; } .buttons button:active { transform: scale(0.99); } .operator { color: #2f9fff; }
JS
Copy
const display = document.querySelector(".display"); const buttons = document.querySelectorAll("button"); const specialChars = ["%", "*", "/", "-", "+", "="]; let output = ""; const calculate = (btnValue) => { display.focus(); if (btnValue === "=" && output !== "") { try { output = eval(output.replace("%", "/100")); } catch { output = "Error"; } } else if (btnValue === "AC") { output = ""; } else if (btnValue === "DEL") { output = output.toString().slice(0, -1); } else { if (specialChars.includes(btnValue) && specialChars.includes(output[output.length - 1])) { return; } if (output === "" && specialChars.includes(btnValue)) return; output += btnValue; } display.value = output; }; buttons.forEach((button) => { button.addEventListener("click", (e) => calculate(e.target.dataset.value)); }); document.addEventListener("keydown", (event) => { const key = event.key; const allowedKeys = [...Array(10).keys(), ".", "Enter", "Backspace", "%", "*", "/", "-", "+"]; if (allowedKeys.includes(key) || key === "Backspace") { let value = key === "Enter" ? "=" : key; value = key === "Backspace" ? "DEL" : value; calculate(value); } });