Set Cursor Position of textarea with JavaScript Set Cursor Position of textarea with JavaScript

In the following example, I will create some basic functions to allow you to set where the cursor goes inside of a textarea or <input type="text">. Let's dive right into the core JavaScript code that will leverage similar functions to a JavaScript array:


Using setSelectionRange and createTextRange


function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function setCaretToPos (input, pos) {
setSelectionRange(input, pos, pos);
}

To execute the code, it would be done as follows:

setCaretToPos(document.getElementById("testinput"), 8);

So, assuming you have a textarea with the id of testinput created on your page, the cursor position will be set after the 8th character in the textarea. On occasion you may get errors like How to check for undefined in JavaScript so hopefully this will help.

Explaining moveEnd and moveStart

The above code could then be updated to use the equivalent getSelectionRange of the textarea when a user clicks a button, insert your code, then move the cursor to the end of the newly inserted code.

By using the setSelectionRange or the createTextRange, it will allow you to set the mouse cursor position of a form element item such as a textarea, input box, etc…

Published on Feb 14, 2019

Tags: JavaScript | setSelectionRange | createTextRange

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.