From 0455d91928e270cd3f2e2798208ca1dfd1123aa1 Mon Sep 17 00:00:00 2001 From: filifa Date: Thu, 11 Dec 2025 23:49:34 -0500 Subject: [PATCH] add backspace function --- main.js | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/main.js b/main.js index 7a80389..a3ed6e6 100644 --- a/main.js +++ b/main.js @@ -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