<!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>
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* Custom styles for better visual appeal if needed, or to ensure font loading */
body {
font-family: 'Inter', sans-serif; /* Ensure Tailwind's default font stack is used or specify one */
}
/* Ensuring button text is centered properly and they have a minimum height */
.calc-button {
display: flex;
justify-content: center;
align-items: center;
min-height: 60px; /* Adjust as needed */
}
/* Style for the display to prevent text overflow and ensure readability */
#display {
overflow-wrap: break-word;
word-break: break-all; /* Break long numbers to prevent overflow */
min-height: 80px; /* Ensure display has a good height */
line-height: 1.2; /* Adjust line height for multi-line results */
}
</style>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
</head>
<body class="bg-slate-100 flex items-center justify-center min-h-screen">
<div class="calculator-container bg-slate-800 shadow-2xl rounded-xl p-6 w-full max-w-xs md:max-w-sm">
<div id="display" class="bg-slate-900 text-white text-4xl md:text-5xl text-right p-4 rounded-lg mb-6 h-24 flex items-end justify-end">
<span id="display-text">0</span>
</div>
<div id="message-area" class="text-red-400 text-sm h-6 mb-2 text-center"></div>
<div class="grid grid-cols-4 gap-3">
<button data-action="clear" class="calc-button bg-red-500 hover:bg-red-600 text-white text-2xl font-semibold rounded-lg col-span-2 transition-colors">C</button>
<button data-action="delete" class="calc-button bg-slate-600 hover:bg-slate-700 text-white text-2xl font-semibold rounded-lg transition-colors">DEL</button>
<button data-operator="/" class="calc-button bg-amber-500 hover:bg-amber-600 text-white text-2xl font-semibold rounded-lg transition-colors">/</button>
<button data-number="7" class="calc-button bg-slate-700 hover:bg-slate-600 text-white text-2xl font-semibold rounded-lg transition-colors">7</button>
<button data-number="8" class="calc-button bg-slate-700 hover:bg-slate-600 text-white text-2xl font-semibold rounded-lg transition-colors">8</button>
<button data-number="9" class="calc-button bg-slate-700 hover:bg-slate-600 text-white text-2xl font-semibold rounded-lg transition-colors">9</button>
<button data-operator="*" class="calc-button bg-amber-500 hover:bg-amber-600 text-white text-2xl font-semibold rounded-lg transition-colors">*</button>
<button data-number="4" class="calc-button bg-slate-700 hover:bg-slate-600 text-white text-2xl font-semibold rounded-lg transition-colors">4</button>
<button data-number="5" class="calc-button bg-slate-700 hover:bg-slate-600 text-white text-2xl font-semibold rounded-lg transition-colors">5</button>
<button data-number="6" class="calc-button bg-slate-700 hover:bg-slate-600 text-white text-2xl font-semibold rounded-lg transition-colors">6</button>
<button data-operator="-" class="calc-button bg-amber-500 hover:bg-amber-600 text-white text-2xl font-semibold rounded-lg transition-colors">-</button>
<button data-number="1" class="calc-button bg-slate-700 hover:bg-slate-600 text-white text-2xl font-semibold rounded-lg transition-colors">1</button>
<button data-number="2" class="calc-button bg-slate-700 hover:bg-slate-600 text-white text-2xl font-semibold rounded-lg transition-colors">2</button>
<button data-number="3" class="calc-button bg-slate-700 hover:bg-slate-600 text-white text-2xl font-semibold rounded-lg transition-colors">3</button>
<button data-operator="+" class="calc-button bg-amber-500 hover:bg-amber-600 text-white text-2xl font-semibold rounded-lg transition-colors">+</button>
<button data-number="0" class="calc-button bg-slate-700 hover:bg-slate-600 text-white text-2xl font-semibold rounded-lg col-span-2 transition-colors">0</button>
<button data-number="." class="calc-button bg-slate-700 hover:bg-slate-600 text-white text-2xl font-semibold rounded-lg transition-colors">.</button>
<button data-action="equals" class="calc-button bg-emerald-500 hover:bg-emerald-600 text-white text-2xl font-semibold rounded-lg transition-colors">=</button>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
// DOM Elements
const displayElement = document.getElementById('display-text');
const messageArea = document.getElementById('message-area');
const buttons = document.querySelectorAll('.calc-button');
// Calculator State
let currentInput = '0'; // Stores the current number being entered or the result
let previousInput = ''; // Stores the first operand
let operator = null; // Stores the selected operator (+, -, *, /)
let shouldResetDisplay = false; // Flag to reset display on next number input
let calculationPerformed = false; // Flag to check if equals was just pressed
// Function to update the display
function updateDisplay() {
// Limit display length to prevent overflow, adjust as needed
const maxLength = 15;
if (currentInput.length > maxLength) {
displayElement.textContent = parseFloat(currentInput).toExponential(6); // Use scientific notation for very long numbers
} else {
displayElement.textContent = currentInput;
}
// Clear any previous messages
messageArea.textContent = '';
}
// Function to display error messages
function showMessage(message) {
messageArea.textContent = message;
setTimeout(() => { messageArea.textContent = ''; }, 3000); // Clear message after 3 seconds
}
// Function to handle number input
function appendNumber(number) {
if (calculationPerformed) { // If equals was just pressed, start new input
currentInput = '';
calculationPerformed = false;
}
if (currentInput === '0' || shouldResetDisplay) {
if (number === '.' && currentInput.includes('.')) return; // Prevent multiple decimals if display was reset to '0.'
currentInput = (number === '.' && currentInput === '0') ? '0.' : number;
shouldResetDisplay = false;
} else {
if (number === '.' && currentInput.includes('.')) return; // Prevent multiple decimals
currentInput += number;
}
updateDisplay();
}
// Function to handle operator selection
function chooseOperator(selectedOperator) {
if (operator && !shouldResetDisplay && currentInput !== '') { // If there's a pending operation and new input, calculate first
calculate();
}
if (currentInput === '' && previousInput === '') return; // Do nothing if no input
if (currentInput !== '') { // Only set previousInput if currentInput is not empty
previousInput = currentInput;
}
operator = selectedOperator;
shouldResetDisplay = true;
calculationPerformed = false; // Reset this flag when an operator is chosen
// Optionally, display the operator or previous input here if desired
// For now, display just resets on next number input
}
// Function to perform calculation
function calculate() {
if (!operator || previousInput === '' || currentInput === '') return; // Need two operands and an operator
let result;
const prev = parseFloat(previousInput);
const current = parseFloat(currentInput);
if (isNaN(prev) || isNaN(current)) {
showMessage("Invalid Input");
hardClear(); // Clear everything on invalid input
return;
}
switch (operator) {
case '+':
result = prev + current;
break;
case '-':
result = prev - current;
break;
case '*':
result = prev * current;
break;
case '/':
if (current === 0) {
showMessage("Cannot divide by zero!");
hardClear(); // Clear everything
return;
}
result = prev / current;
break;
default:
return;
}
// Format result to a reasonable number of decimal places if it's a float
if (result % 1 !== 0) {
result = parseFloat(result.toFixed(10)); // Limit to 10 decimal places and remove trailing zeros
}
currentInput = result.toString();
operator = null;
previousInput = ''; // Clear previousInput after calculation
shouldResetDisplay = true; // Next number input will start fresh
calculationPerformed = true; // Set flag that equals was pressed
updateDisplay();
}
// Function to clear current input or all if current is '0'
function softClear() {
currentInput = '0';
previousInput = '';
operator = null;
shouldResetDisplay = false;
calculationPerformed = false;
updateDisplay();
}
// Function for hard clear (resets everything)
function hardClear() {
currentInput = '0';
previousInput = '';
operator = null;
shouldResetDisplay = false;
calculationPerformed = false;
updateDisplay();
showMessage(''); // Clear any error messages
}
// Function to delete the last character
function deleteLastCharacter() {
if (calculationPerformed) { // If equals was just pressed, clear instead of deleting
softClear();
return;
}
if (currentInput.length > 1 && currentInput !== '0') {
currentInput = currentInput.slice(0, -1);
} else {
currentInput = '0'; // If only one digit or '0', reset to '0'
}
shouldResetDisplay = false; // Allow further typing
updateDisplay();
}
// Event Listeners for buttons
buttons.forEach(button => {
button.addEventListener('click', () => {
const { number, operator: op, action } = button.dataset;
if (number) {
appendNumber(number);
} else if (op) {
chooseOperator(op);
} else if (action) {
if (action === 'clear') {
hardClear();
} else if (action === 'equals') {
calculate();
} else if (action === 'delete') {
deleteLastCharacter();
}
}
});
});
// Keyboard Support
document.addEventListener('keydown', (event) => {
if (event.key >= '0' && event.key <= '9') {
appendNumber(event.key);
} else if (event.key === '.') {
appendNumber('.');
} else if (event.key === '+' || event.key === '-' || event.key === '*' || event.key === '/') {
chooseOperator(event.key);
} else if (event.key === 'Enter' || event.key === '=') {
event.preventDefault(); // Prevent default form submission if inside one
calculate();
} else if (event.key === 'Backspace') {
deleteLastCharacter();
} else if (event.key === 'Escape' || event.key.toLowerCase() === 'c') {
hardClear();
}
});
// Initial display update
updateDisplay();
});
</script>
</body>
</html>
AI is still inaccurate. We try to vet the obvious errors within our ability. Please comment if you see an error!
Search This Blog
Friday, May 9, 2025
ffff
Subscribe to:
Post Comments (Atom)
A Matter of Degree
Throughout the Bible, God has given us warnings. Warnings that are not meant to bring fear into our lives, but rather these warnings are m...
-
Notebook LM: AI Mind Map FAQ FAQ on AI-Powered Personal Knowledge Management and Mind Mapping 1. What is Notebook LM's new mind map fe...
-
Of course. Here is a detailed look at the academic performance of schools in Pocahontas County, based on the 2023-2024 data provided. Poca...
-
Each Student should cover a specific board member as they vote! Make sure they all vote and you know how they voted! This is the 21st ...
No comments:
Post a Comment