How to Position a Dropdown at Cursor Position Inside a Textarea

Dropdown value patch based on cursor position in textarea

you need take account the "selectionStart" and selectionEnd of the textArea. For this, create a template reference variable and pass to the function

<!--see the #text-->
<textarea #text [(ngModel)]='textValue' rows="10" cols="70">
</textarea>
...
<!--pass the "variable" to the function changeValue-->
<mat-select (change)="changeValue($event,text)">
...
</mat-select>

Then your function changeValue

  changeValue(ev,textArea:any) {
const posInitial=textArea.selectionStart;
const posFinal=textArea.selectionEnd;
this.textValue = this.textValue.substr(0,posInitial)+
ev.value+
this.textValue.substr(posFinal);
}

NOTE: If you don't want pass the "text" to the function you can also use ViewChild

@ViewChild("text") textArea:ElementRef

And to get the positions using

const posInitial=this.textArea.nativeElement.selectionStart;
const posFinal=this.textArea.nativeElement.selectionEnd;

See that in this case you use this.textArea.ElementRef

stackblitz

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>

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);
});
});


Related Topics



Leave a reply



Submit