Helping you solve those tough coding problems!

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

Published on Feb 14, 2019 by Jamie Munro

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:




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.

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…

Tags: JavaScript | setSelectionRange | createTextRange

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP