Hey Form
I’m trying to get the cursor position in an Input (textBox) as a person types.
E.g. something similar to :
I assume it would be something like this:
exportfunctiontextBox1_keyPress(event) {
const cursorPosition = event.target.selectionStart;
console.log(cursorPosition);
}
However, this returns “undefined”
Is there a Wix native/javascript workaround without building a custom element?
Many thanks!
Ok, what do we have?
- We have a text-input-filed!
https://www.wix.com/velo/reference/$w/textinput
Which function do we want to achieve?
You want to get back the current position of your cursor, while typing into the INPUT-BOX.
What kind of possibilities do we have?
a) onClick ---------> seems not to be the right one
b) onMouseIn ----> seems not to be the right one
c) onMouseOut → seems not to be the right one
d) onChange ------> hmmm we are getting closer
e) onKeyPress( ) → ho! whats that?
Yes you already recognized this and also used the right one in your code.
So what next???
You also already use the → EVENT-OUTPUT ← but you didn’t do it completely.
Try out the following and take a look onto → CONSOLE and it’s RESULT-OUTPUT.
$w.onReady(async()=> {
$w('#input1').onKeyPress((event) => {
console.log("POS: ", event.target.value.length);
});
});
Hey Velo-Ninja
All this seems to do is just return the value length of the text in the box?
Below I typed “test” then backspace twice. It keeps returning “4” (the length of the characters in the text box).
With the below example it needs to return “2”, the position of the cursor in the box.

So that means “BACKSPACE” is not included in the onKeyPress-trigger-event.
Maybe you can find more info reading this one…
Try to capture “BACKSPACE-KEY”
Here a example with the ENTER-KEY…
$w.onReady(function () {
$w('#input1').onKeyPress((event) => {
console.log("Pressed-Key: ", event.key);
if(event.key === "Enter"){ console.log("ENTER clicked!"); }
});
});
Take a look onto console, and inspect the logs, to see if you get some KEY-RESULT when pressing the BACKSPACE-BUTTON on your Keyboard.
I don’t think you fully understand what I’m trying to achieve? I’m wanting to return the character position of the cursor.
With your code, even if I click the cursor to position “1”, then type “b” again, it still returns “5”. I’m wanting it to return position “2”. E.g., the cursor is in the 2nd character position. All this is doing is returning the total length of the text in the textBox >>

I don’t think you can do it using Wix/Velo offered options.
But maybe you can find something interessting here…
https://www.wix.com/velo/reference/$w/mouseevent
But i still think it is not possible without using an HTML-component or custom-element.