Set keyboard caret position in html textbox

how to set cursor position in textbox in html
set caret position javascript contenteditable
how to set cursor position in textarea in html
javascript set cursor position in textarea
textarea set cursor position to end
jquery set cursor position in textbox to the start
input cursor position css
html autofocus cursor position

Does anybody know how to move the keyboard caret in a textbox to a particular position?

For example, if a text-box (e.g. input element, not text-area) has 50 characters in it and I want to position the caret before character 20, how would I go about it?

This is in differentiation from this question: jQuery Set Cursor Position in Text Area , which requires jQuery.

Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript

A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.

Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).

An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:

function addLoadEvent(func) {
    if(typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        if(func) {
            var oldLoad = window.onload;

            window.onload = function() {
                if(oldLoad)
                        oldLoad();

                func();
            }
        }
    }
}

// The setCaretPosition function belongs right here!

function setTextAreasOnFocus() {
/***
 * This function will force the keyboard caret to be positioned
 * at the end of all textareas when they receive focus.
 */
    var textAreas = document.getElementsByTagName('textarea');

    for(var i = 0; i < textAreas.length; i++) {
        textAreas[i].onfocus = function() {
            setCaretPosition(this.id, this.value.length);
        }
    }

    textAreas = null;
}

addLoadEvent(setTextAreasOnFocus);

Set keyboard caret position in html textbox, Does anybody know how to move the keyboard caret in a textbox to a particular position? For example, if a text-box (e.g. input element, not  JavaScript Get & Set Cursor Position in Textarea 8 months ago admin Text & Input 0 The Caret is a lightweight jQuery plugin that makes it easy to get & set cursor position with JavaScript in textarea.

The link in the answer is broken, this one should work (all credits go to blog.vishalon.net):

http://snipplr.com/view/5144/getset-cursor-in-html-textarea/

In case the code gets lost again, here are the two main functions:

function doGetCaretPosition(ctrl)
{
 var CaretPos = 0;

 if (ctrl.selectionStart || ctrl.selectionStart == 0)
 {// Standard.
  CaretPos = ctrl.selectionStart;
 }
 else if (document.selection)
 {// Legacy IE
  ctrl.focus ();
  var Sel = document.selection.createRange ();
  Sel.moveStart ('character', -ctrl.value.length);
  CaretPos = Sel.text.length;
 }

 return (CaretPos);
}


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

Set keyboard caret position in html textbox, Does anybody know how to move the keyboard caret in a textbox to a particular position? For example, if a text-box (e.g. input element, not  Get or Set Cursor Position in a Textarea, javascript – How do you get the cursor position in a textarea, jQuery Set Cursor Position in Text Area, Get cursor position (in characters) within a text Input field, Caret position in textarea, in characters from the start, Javascript : Getting and Setting Caret Position in Textarea, JavaScript: Set Cursor

Since I actually really needed this solution, and the typical baseline solution (focus the input - then set the value equal to itself) doesn't work cross-browser, I spent some time tweaking and editing everything to get it working. Building upon @kd7's code here's what I've come up with.

Enjoy! Works in IE6+, Firefox, Chrome, Safari, Opera

Cross-browser caret positioning technique (example: moving the cursor to the END)

// ** USEAGE ** (returns a boolean true/false if it worked or not)
// Parameters ( Id_of_element, caretPosition_you_want)

setCaretPosition('IDHERE', 10); // example

The meat and potatoes is basically @kd7's setCaretPosition, with the biggest tweak being if (el.selectionStart || el.selectionStart === 0), in firefox the selectionStart is starting at 0, which in boolean of course is turning to False, so it was breaking there.

In chrome the biggest issue was that just giving it .focus() wasn't enough (it kept selecting ALL of the text!) Hence, we set the value of itself, to itself el.value = el.value; before calling our function, and now it has a grasp & position with the input to use selectionStart.

function setCaretPosition(elemId, caretPos) {
    var el = document.getElementById(elemId);

    el.value = el.value;
    // ^ this is used to not only get "focus", but
    // to make sure we don't have it everything -selected-
    // (it causes an issue in chrome, and having it doesn't hurt any other browser)

    if (el !== null) {

        if (el.createTextRange) {
            var range = el.createTextRange();
            range.move('character', caretPos);
            range.select();
            return true;
        }

        else {
            // (el.selectionStart === 0 added for Firefox bug)
            if (el.selectionStart || el.selectionStart === 0) {
                el.focus();
                el.setSelectionRange(caretPos, caretPos);
                return true;
            }

            else  { // fail city, fortunately this never happens (as far as I've tested) :)
                el.focus();
                return false;
            }
        }
    }
}

Cross browser Javascript code to get/set caret position in textarea , Set keyboard caret position in html textbox - Does anybody know how to move the keyboard caret in a textbox to a particular position? For example, if a text-box​  Set Cursor Position In Text Area Using Angular 2 . myInput.value)" >Set Caret Position Here in below examples we can see how to set text or html to an element

I've adjusted the answer of kd7 a little bit because elem.selectionStart will evaluate to false when the selectionStart is incidentally 0.

function setCaretPosition(elem, caretPos) {
    var range;

    if (elem.createTextRange) {
        range = elem.createTextRange();
        range.move('character', caretPos);
        range.select();
    } else {
        elem.focus();
        if (elem.selectionStart !== undefined) {
            elem.setSelectionRange(caretPos, caretPos);
        }
    }
}

Setting the cursor position with JavaScript, Here is a working snippet of code to get and set the caret position in HTML textarea and textbox. This code works for IE 6, 7, 8, >=9, Firefox, Chrome, Safari and  To position the cursor at the end of the contents of a TextBox control, call the Select method and specify the selection start position equal to the length of the text content, and a selection length of 0. tbPositionCursor.Select(tbPositionCursor.Text.Length, 0)

If you need to focus some textbox and your only problem is that the entire text gets highlighted whereas you want the caret to be at the end, then in that specific case, you can use this trick of setting the textbox value to itself after focus:

$("#myinputfield").focus().val($("#myinputfield").val());

jQuery/HTML5 Input Focus and Cursor Positions, A simple snippet of code showing how you can set the position of the cursor within a text input field, this should work in at least IE8+ and all modern Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript. A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:

How to get the current cursor position (and selection) within a text , jQuery Set Cursor Position. jQuery function to set the cursor position to a specfic character position within an input field. //SET CURSOR  Setting cursor at the end of any text of a textbox [duplicate] Asked 5 years, 11 months ago. Active 1 year ago. Viewed 162k times. This question already has answers here : Set the caret/cursor position to the end of the string value WPF textbox (6 answers) Closed 5 years ago. I have a text box with a displayed string already in it. To bring the

javascript - Caret position cross browser?, Retrieve the position of the cursor (caret) within a textarea is easier These values (start and end) provide always an integer value with the index of the selected text within a textarea or text input. JavaScript; HTML; Result. Step 1: TextBox.CaretIndex property will give you the index of the caret in the overall string. Step 2: TextBox.GetCharacterIndexFromLine() can give you the starting index of each line. Given this information, you can (A) figure out in which line the current caret index is, and (B) what the relative index/position of the caret is in relation to the starting index of that line.

component/textarea-caret-position: xy coordinates of a , in an input type text (not a tex javascript html textinput caret javascript - Set keyboard caret position in html textbox - Stack Overf javascript textbox input. jQuery Set Cursor Position. jQuery function to set the cursor position to a specfic character position within an input field.

Comments
  • if(elem.selectionStart) breaks when selectionStart is 0 as also pointed out by jhnns's answer.
  • This doesn't work for me. When I click the actual textbox I have I expect the caret position to be in the beginning. Check out my fiddle jsfiddle.net/khx2w
  • The setCaretPosition function works just fine. Your addActionHandler function, however, does not. But even without that, I could not get the cursor to move on focus. Most likely, it's because the browser sets the cursor position itself based on the position of the click. There doesn't seem to be a way around it from what I can tell, but I could be completely wrong.
  • Works in IE9, FF25, but not Chrome 30. Better than none!
  • I have elem.value = elem.value.replace(/^9/g,'+79') in code. On OperaMINI cursor after +. this function not helps
  • +1 for the base functions, though some adjustments have to be made. The number of lines has to be substracted from "pos", when using the range method.
  • Thank you very much :)
  • Anytime, glad it's getting some use elsewhere! @Mr_Green
  • @mcpDESIGNS I'm trying to use this function when a focus is made on a text input, but I'm getting nowhere, Could you please help with applying this function using pure javascript?
  • @elad.chen Are you trying to position them to the end of the textbox as soon as they focus on it?
  • el.value = el.value; [...] if(el !== null) - I would swap these two lines. If el is null, el.value = el.value will fail, so that line should be inside the if.
  • Uncaught TypeError: Object [object HTMLInputElement] has no method 'startsWith'
  • @bobpaul: tID should be the id of the element, not the element object itself. If you are passing the element object, you can just remove the 2 first lines in this method, and it will work.