Search/static/js/calculator.js
partisan fa266ec993
Some checks failed
Run Integration Tests / test (push) Failing after 41s
Fixed calc in Instant Answers
2025-06-26 17:47:12 +02:00

53 lines
1.8 KiB
JavaScript

document.addEventListener('DOMContentLoaded', function () {
const calcContainer = document.getElementById('dynamic-calc');
const staticCalc = document.getElementById('static-calc');
if (calcContainer) {
calcContainer.style.display = 'block';
if (staticCalc) staticCalc.style.display = 'none';
const input = document.getElementById('calc-input');
const history = document.getElementById('calc-history');
const buttons = document.querySelectorAll('.calc-buttons button');
const staticCalcContent = staticCalc?.textContent.trim(); // load HTML calc
const initialQuery = input.value.trim();
let currentInput = initialQuery;
let historyLog = [];
if (initialQuery && staticCalcContent) {
historyLog.push(`${initialQuery} = ${staticCalcContent}`);
}
const updateUI = () => {
input.value = currentInput;
history.innerHTML = historyLog.map(entry => `<div>${entry}</div>`).join('');
};
buttons.forEach(button => {
button.addEventListener('click', () => {
const val = button.getAttribute('data-value');
if (val === 'C') {
currentInput = '';
} else if (val === '=') {
try {
const res = eval(currentInput);
historyLog.push(`${currentInput} = ${res}`);
if (historyLog.length > 30) historyLog.shift(); // Remove oldest
currentInput = res.toString();
} catch (e) {
currentInput = 'Error';
}
} else {
currentInput += val;
}
updateUI();
});
});
updateUI();
}
});