Sometimes, we want to insert text into a text area at the current cursor position.
In this article, we’ll look at how to insert text into the text area at the current cursor position.
Use the setRangeText Method
We can use the setRangeText method to add text at the current cursor position.
For instance, if we have the following input:
<input id="input"/>
Then we can write the following JavaScript code to add the text at the cursor position when we press the Enter key when the cursor is in the input:
const typeInTextarea = (newText, el = document.activeElement) => {
const [start, end] = [el.selectionStart, el.selectionEnd];
el.setRangeText(newText, start, end, 'select');
}
document.getElementById("input").onkeydown = e => {
if (e.key === "Enter") {
typeInTextarea("abc");
}
}
We create the typeInTextarea function that has the newText parameter with the text we want to insert.
And it has the el element that has the element we want to insert the text to.
document.activeElement is the current element that’s focused on.
In the function, we get the selection start and selection end with selectionStart and selectionEnd .
Then we call setRangeText with the newText , start , end and 'selection' to add the newText at the current cursor position.
Then we have the onkeydown property set to a function that calls the typeInTextarea function with the text we want to insert with the enter key is pressed.
Conclusion
We can insert text into an input at the cursor position when we press a key with the setRangeText method.
One reply on “How to Insert Text into the Text Area at the Current Cursor Position?”
selectionStart, selectionEnd, setRangeText doesn’t exists on type element