How to Get the Cursor Position in a Textarea

How do you get the cursor position in a textarea?

If there is no selection, you can use the properties .selectionStart or .selectionEnd (with no selection they're equal).

var cursorPosition = $('#myTextarea').prop("selectionStart");

Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.

I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.

Set text-cursor position in a textarea

After refocusing the textarea with txtarea.focus(), add this line:

txtarea.selectionEnd= end + 7;

That will set the cursor seven positions ahead of where it was previously, which will take [b][/b] into account.

Example

document.getElementById('bold').addEventListener('click', boldText);
function boldText() { var txtarea = document.getElementById("editor_area"); var start = txtarea.selectionStart; var end = txtarea.selectionEnd; var sel = txtarea.value.substring(start, end); var finText = txtarea.value.substring(0, start) + '[b]' + sel + '[/b]' + txtarea.value.substring(end); txtarea.value = finText; txtarea.focus(); txtarea.selectionEnd= end + 7;}
#editor_area {  width: 100%;  height: 10em;}
<button id="bold">B</button><textarea id="editor_area"></textarea>

How to set cursor position in a textarea where I last inserted the text?

Simply use this selectionEnd and sum with txt_to_add length

$(document).ready(function() {
// Get current cursor position $("#btngetcurpos").click(function() { var cursor_pos = $("#my_textarea").prop('selectionStart'); alert(cursor_pos); $("#my_textarea").focus(); });
// Insert text at current cursor position $("#btnsettxt").click(function() { var cursor_pos = $("#my_textarea").prop('selectionStart'); var textarea_txt = $("#my_textarea").val(); var txt_to_add = "test"; $("#my_textarea").val(textarea_txt.substring(0, cursor_pos) + txt_to_add + textarea_txt.substring(cursor_pos)); $("#my_textarea").focus(); $('#my_textarea').prop('selectionEnd', cursor_pos + txt_to_add.length);
});});
#my_textarea {  border: 1px solid red;  width: 300px;  height: 100px;  padding: 5px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<textarea id="my_textarea" autofocus>This is a textarea.</textarea>
<br /><br />
<input type="button" id="btngetcurpos" value="Get Cursor Position" />
<input type="button" id="btnsettxt" value="Insert Text" />

Get cursor position when a file is dropped in textarea in Chrome

Phew, what you want to do isn't easy, since there is no way to reference this specific caret!

Off the top of my head, you could only implement this through heavy workarounds: What you can obtain upon drop occuring is the mouse cursor position.

You would have to make an invisible div-clone identical to the textarea in shape, text-size, margins, etc that automatically gets filled with the text from your textarea.

Next you'd have to create a span for each possible caret position (i.e. 1 span for every character of text) inside this div and get each span's x and y coordinates and save them into an array.

.txtarea {
width: 300px;
height: 150px;
font-size: 12px;
font-family: Arial;
padding: 5px;
text-align: left;
border: 1px solid red;
}
<textarea class="txtarea">Mytext</textarea>

<!--just an example, auto-fill this content through a JS oninput event -->
<div class="txtarea"><span>M</span><span>y</span><span>t</span><span>e</span><span>x</span><span>t</span></div>

Get cursor position (in characters) within a text Input field

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:

/*
** Returns the caret (cursor) position of the specified text field (oField).
** Return value range is 0-oField.value.length.
*/
function doGetCaretPosition (oField) {

// Initialize
var iCaretPos = 0;

// IE Support
if (document.selection) {

// Set focus on the element
oField.focus();

// To get cursor position, get empty selection range
var oSel = document.selection.createRange();

// Move selection start to 0 position
oSel.moveStart('character', -oField.value.length);

// The caret position is selection length
iCaretPos = oSel.text.length;
}

// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd;

// Return results
return iCaretPos;
}

get text under current cursor positon inside a textarea

You are wellcome,

var borderChars = [' ', '\n', '\r', '\t']
$(function() {
$('textarea').on('click', function() {
var text = $(this).html();
var start = $(this)[0].selectionStart;
var end = $(this)[0].selectionEnd;
while (start > 0) {
if (borderChars.indexOf(text[start]) == -1) {
--start;
} else {
break;
}
}
++start;
while (end < text.length) {
if (borderChars.indexOf(text[end]) == -1) {
++end;
} else {
break;
}
}
var currentWord = text.substr(start, end - start);
console.log(currentWord);
});
});

How to find X and Y position of text caret/cursor

You can't get the exact coordinates of the text caret effortlessly, but this snippet will give you a rect object with the approximate coordinates of the window's current selection. You may have to also add/subtract use additional offsets of containing elements depending on your styling.

const selection = window.getSelection();
const range = selection.getRangeAt(0);
rect = range.getBoundingClientRect();

Change the cursor position in a textarea with React

You have to change the cursor position after the state has been updated(setState() does not immediately mutate this.state)

In order to do that, you have to wrap this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1; in a function and pass it as the second argument to setState (callback).

handleKeyDown(event) {
if (event.keyCode === 9) { // tab was pressed
event.preventDefault();
var val = this.state.scriptString,
start = event.target.selectionStart,
end = event.target.selectionEnd;
this.setState(
{
"scriptString": val.substring(0, start) + '\t' + val.substring(end)
},
() => {
this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1
});
}
}

jsfiddle

Angular - How to set caret position in textarea

Focussing elements in Angular is often a difficult thing to implement. Although, it looks like your code is working when using a FormControl instead of ngModel (working stackblitz):

Template:

<textarea #textArea [formControl]="formControl"></textarea>

Component:

@ViewChild('textArea') _textArea: ElementRef;

formControl = new FormControl(this.title);

ngAfterViewInit(): void {
const textArea = this._textArea.nativeElement as HTMLTextAreaElement;
textArea.focus()
textArea.setSelectionRange(0, 0);
}

Module (add ReactiveFormsModule to imports if not present yet):

@NgModule({
imports: [ BrowserModule, FormsModule, ReactiveFormsModule ]
})

You'll definitely need the focus() cause setSelectionRange only sets the cursor and wont have much use without focus.



Related Topics



Leave a reply



Submit