How can I get the caret position from within an input field?
I have found a few bits and pieces via Google, but nothing bullet proof.
Basically something like a jQuery plugin would be ideal, so I could simply do
$("#myinput").caretPosition()
How can I get the caret position from within an input field?
I have found a few bits and pieces via Google, but nothing bullet proof.
Basically something like a jQuery plugin would be ideal, so I could simply do
$("#myinput").caretPosition()
Easier update:
Use
field.selectionStart
example in this answer.Thanks to @commonSenseCode for pointing this out.
Old answer:
Found this solution. Not jquery based but there is no problem to integrate it to jquery:
There is now a nice plugin for this: The Caret Plugin
Then you can get the position using
$("#myTextBox").caret()
or set it via$("#myTextBox").caret(position)
Nice one, big thanks to Max.
I've wrapped the functionality in his answer into jQuery if anyone wants to use it.
Got a very simple solution. Try the following code with verified result-
I'm giving you the fiddle_demo
Perhaps you need a selected range in addition to cursor position. Here is a simple function, you don't even need jQuery:
Let's say you wanna call it on an input whenever it changes or mouse moves cursor position (in this case we are using jQuery
.on()
). For performance reasons, it may be a good idea to addsetTimeout()
or something like Underscores_debounce()
if events are pouring in:Here is a fiddle if you wanna try it out: https://jsfiddle.net/Dhaupin/91189tq7/