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()
This question is related to
javascript
jquery
html
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)
There are a few good answers posted here, but I think you can simplify your code and skip the check for inputElement.selectionStart
support: it is not supported only on IE8 and earlier (see documentation) which represents less than 1% of the current browser usage.
var input = document.getElementById('myinput'); // or $('#myinput')[0]
var caretPos = input.selectionStart;
// and if you want to know if there is a selection or not inside your input:
if (input.selectionStart != input.selectionEnd)
{
var selectionValue =
input.value.substring(input.selectionStart, input.selectionEnd);
}
Perhaps you need a selected range in addition to cursor position. Here is a simple function, you don't even need jQuery:
function caretPosition(input) {
var start = input[0].selectionStart,
end = input[0].selectionEnd,
diff = end - start;
if (start >= 0 && start == end) {
// do cursor position actions, example:
console.log('Cursor Position: ' + start);
} else if (start >= 0) {
// do ranged select actions, example:
console.log('Cursor Position: ' + start + ' to ' + end + ' (' + diff + ' selected chars)');
}
}
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 add setTimeout()
or something like Underscores _debounce()
if events are pouring in:
$('input[type="text"]').on('keyup mouseup mouseleave', function() {
caretPosition($(this));
});
Here is a fiddle if you wanna try it out: https://jsfiddle.net/Dhaupin/91189tq7/
const inpT = document.getElementById("text-box");_x000D_
const inpC = document.getElementById("text-box-content");_x000D_
// swch gets inputs ._x000D_
var swch;_x000D_
// swch if corsur is active in inputs defaulte is false ._x000D_
var isSelect = false;_x000D_
_x000D_
var crnselect;_x000D_
// on focus_x000D_
function setSwitch(e) {_x000D_
swch = e;_x000D_
isSelect = true;_x000D_
console.log("set Switch: " + isSelect);_x000D_
}_x000D_
// on click ev_x000D_
function setEmoji() {_x000D_
if (isSelect) {_x000D_
console.log("emoji added :)");_x000D_
swch.value += ":)";_x000D_
swch.setSelectionRange(2,2 );_x000D_
isSelect = true;_x000D_
}_x000D_
_x000D_
}_x000D_
// on not selected on input . _x000D_
function onout() {_x000D_
// ?????? ??? ?? ?? _x000D_
crnselect = inpC.selectionStart;_x000D_
_x000D_
// return input select not active after 200 ms ._x000D_
var len = swch.value.length;_x000D_
setTimeout(() => {_x000D_
(len == swch.value.length)? isSelect = false:isSelect = true;_x000D_
}, 200);_x000D_
}
_x000D_
<h1> Try it !</h1>_x000D_
_x000D_
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box" size="20" value="title">_x000D_
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box-content" size="20" value="content">_x000D_
<button onclick="setEmoji()">emogi :) </button>
_x000D_
Use selectionStart
, it is compatible with all major browsers.
document.getElementById('foobar').addEventListener('keyup', e => {
console.log('Caret at: ', e.target.selectionStart)
})
_x000D_
<input id="foobar" />
_x000D_
Update: This works only when no type is defined or type="text"
or type="textarea"
on the input.
Nice one, big thanks to Max.
I've wrapped the functionality in his answer into jQuery if anyone wants to use it.
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if (document.selection) {
// IE
input.focus();
}
return 'selectionStart' in input ? input.selectionStart:'' || Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
}
})(jQuery);
Got a very simple solution. Try the following code with verified result-
<html>
<head>
<script>
function f1(el) {
var val = el.value;
alert(val.slice(0, el.selectionStart).length);
}
</script>
</head>
<body>
<input type=text id=t1 value=abcd>
<button onclick="f1(document.getElementById('t1'))">check position</button>
</body>
</html>
I'm giving you the fiddle_demo
Source: Stackoverflow.com