From 5d004370e3b394f25bdadc6e4d0727f74c127184 Mon Sep 17 00:00:00 2001 From: filifa Date: Thu, 11 Dec 2025 23:49:34 -0500 Subject: [PATCH] insert at last cursor position when pressing button --- main.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/main.js b/main.js index e3f91d1..25f0667 100644 --- a/main.js +++ b/main.js @@ -153,9 +153,13 @@ function calculate() { } let currentInput = null; +let selectionStart = null; +let selectionEnd = null; function setCurrentInput() { currentInput = this; + selectionStart = this.selectionStart; + selectionEnd = this.selectionEnd; } function clear() { @@ -164,8 +168,14 @@ function clear() { } function keyPress(c) { - currentInput.value += c; + // FIXME not working with modulus + // errors in logs on each key press + // wonder if it's an issue with it being a number type currentInput.focus(); + const begin = currentInput.value.slice(0, selectionStart); + const end = currentInput.value.slice(selectionEnd); + currentInput.value = begin + c + end; + currentInput.setSelectionRange(selectionEnd+1, selectionEnd+1); } document.querySelector("#expr").addEventListener("focus", setCurrentInput); @@ -195,5 +205,5 @@ document.querySelector("#pow").addEventListener("click", () => keyPress("^")); document.querySelector("#clear").addEventListener("click", clear); document.querySelector("#enter").addEventListener("click", calculate); -// FIXME buttons don't work if you try to insert in the middle of the text -// TODO backspace is probably going to be tricky +// TODO backspace might be tricky +// TODO implement square root and inverse keys