add backspace function

This commit is contained in:
filifa 2025-12-11 23:49:34 -05:00
parent 6edffa672b
commit 0455d91928
1 changed files with 28 additions and 1 deletions

29
main.js
View File

@ -178,6 +178,32 @@ function keyPress(c) {
currentInput.setSelectionRange(selectionStart+1, selectionStart+1);
}
function backspace() {
currentInput.focus();
if (selectionEnd === 0) {
return;
}
let begin = null;
if (selectionStart === selectionEnd) {
begin = currentInput.value.slice(0, selectionStart-1);
} else {
begin = currentInput.value.slice(0, selectionStart);
}
const end = currentInput.value.slice(selectionEnd);
currentInput.value = begin + end;
if (selectionStart === 0) {
currentInput.setSelectionRange(0, 0);
} else if (selectionStart === selectionEnd) {
currentInput.setSelectionRange(selectionStart-1, selectionStart-1);
} else {
currentInput.setSelectionRange(selectionStart, selectionStart);
}
}
document.querySelector("#expr").addEventListener("focus", setCurrentInput);
document.querySelector("#modulus").addEventListener("focus", setCurrentInput);
@ -205,5 +231,6 @@ document.querySelector("#pow").addEventListener("click", () => keyPress("^"));
document.querySelector("#clear").addEventListener("click", clear);
document.querySelector("#enter").addEventListener("click", calculate);
// TODO backspace might be tricky
document.querySelector("#backspace").addEventListener("click", backspace);
// TODO implement square root and inverse keys