jQuery Set Cursor Position in Text Area

jquery set cursor position in textbox to the end
jquery set cursor in input
textarea set cursor position to end
how to set cursor position in textbox in html
how to set cursor position in textarea in html
jquery set cursor to element
jquery setselectionrange
jquery caret position

How do you set the cursor position in a text field using jQuery? I've got a text field with content, and I want the users cursor to be positioned at a certain offset when they focus on the field. The code should look kind of like this:

$('#input').focus(function() {
  $(this).setCursorPosition(4);
});

What would the implementation of that setCursorPosition function look like? If you had a text field with the content abcdefg, this call would result in the cursor being positioned as follows: abcd**|**efg.

Java has a similar function, setCaretPosition. Does a similar method exist for javascript?

Update: I modified CMS's code to work with jQuery as follows:

new function($) {
  $.fn.setCursorPosition = function(pos) {
    if (this.setSelectionRange) {
      this.setSelectionRange(pos, pos);
    } else if (this.createTextRange) {
      var range = this.createTextRange();
      range.collapse(true);
      if(pos < 0) {
        pos = $(this).val().length + pos;
      }
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);

I have two functions:

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

Then you can use setCaretToPos like this:

setCaretToPos(document.getElementById("YOURINPUT"), 4);

Live example with both a textarea and an input, showing use from jQuery:

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

$("#set-textarea").click(function() {
  setCaretToPos($("#the-textarea")[0], 10)
});
$("#set-input").click(function() {
  setCaretToPos($("#the-input")[0], 10);
});
<textarea id="the-textarea" cols="40" rows="4">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
<br><input type="button" id="set-textarea" value="Set in textarea">
<br><input id="the-input" type="text" size="40" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit">
<br><input type="button" id="set-input" value="Set in input">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

jQuery Set Cursor Position in Text Area, You can use these two functions given below: function setSelectionRange(input, selectionStart, selectionEnd) {. if (input.setSelectionRange) {. Set Cursor Position of textarea with JavaScript . Published on Feb 14, 2019. 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

Set caret position via jQuery � GitHub, jQuery Caret. $.fn.caretTo( index , [ offset ] ) This methods first parameter is the index of where you want to move the caret to. $.fn.caretToStart() This is a shortcut for $. $.fn.caretToEnd() This method moves the caret to the end of the content within your element, also for your convenience. Author. License. How do you set the cursor position in a text field using jQuery? I've got a text field with content, and I want the users cursor to be positioned at a certain offset when they focus on the field. The code should look kind of like this: $('#input').focus(function() { $(this).setCursorPosition(4); });

The solutions here are right except for the jQuery extension code.

The extension function should iterate over each selected element and return this to support chaining. Here is the a correct version:

$.fn.setCursorPosition = function(pos) {
  this.each(function(index, elem) {
    if (elem.setSelectionRange) {
      elem.setSelectionRange(pos, pos);
    } else if (elem.createTextRange) {
      var range = elem.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  });
  return this;
};

[jQuery] Set cursor position in textarea/input, i know its of the annoying topics but im using this function to set cursor position: function setSelectionRangeX(input, selectionStart,� 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

I found a solution that works for me:

$.fn.setCursorPosition = function(position){
    if(this.length == 0) return this;
    return $(this).setSelection(position, position);
}

$.fn.setSelection = function(selectionStart, selectionEnd) {
    if(this.length == 0) return this;
    var input = this[0];

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

    return this;
}

$.fn.focusEnd = function(){
    this.setCursorPosition(this.val().length);
            return this;
}

Now you can move the focus to the end of any element by calling:

$(element).focusEnd();

Or you specify the position.

$(element).setCursorPosition(3); // This will focus on the third character.

textarea set cursor position - JSFiddle, <textarea class="texta"></textarea>. 2. <button id="test">test</button>. JavaScript + jQuery 2.0.2 Tidy. xxxxxxxxxx. 19. 1. $('#test').click(function () {. 2. var text� jQuery Set Cursor Position in Text Area ; jQuery Set Cursor Position in Text Area. 0 votes . 1 view. asked Aug 29, 2019 in Web Technology by Tech4ever (22.4k points)

This worked for me on Safari 5 on Mac OSX, jQuery 1.4:

$("Selector")[elementIx].selectionStart = desiredStartPos; 
$("Selector")[elementIx].selectionEnd = desiredEndPos;

Move Cursor To End of Textarea or Input, Code to move the cursor to the end of the current text within in the input, rather than the default (highlighting the text). Plugin format. Home / Code Snippets / jQuery Code Snippets / Move Cursor To End of Textarea or Input. Here is a free jQuery plugin to get & set cursor position through JavaScript in textarea or editable div. The caret plugin helps you to check / set cursor ..

jQuery/HTML5 Input Focus and Cursor Positions, jQuery Set Cursor Position. jQuery function to auto select text (specific number of characters) within an input field. //SELECT TEXT RANGE $. JQUERY Set Textarea Cursor to End of Text. Ask Question Asked 7 years, jQuery Set Cursor Position in Text Area. Most elegant JQuery solution from there:

How to set cursor position in textarea using jQuery?, function setSelectionRange(input, selectionStart, selectionEnd) { if (input. setSelectionRange) { input.focus(); input. I have a textarea and I would like to know if I am on the last line in the textarea or the first line in the textarea with my cursor with JavaScript. I thought of grabbing the position of the first newline character and the last newline character and then grabbing the position of the cursor.

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. jQuery Set Cursor Position. jQuery function to set the cursor position to a specfic character position within an input field. //SET CURSOR POSITION $.fn.setCursorPosition = function(pos) { this

Comments
  • $(this).get(0).setSelectionRange)? You do know that's exactly the same as this.setSelectionRange, only slower and harder to read, right? jQuery is doing literally nothing for you here.
  • To add to @bobince comment, the function should iterate for each of the selected elements and return this. The correct code is in my answer.
  • @bobince is actually not quite correct either. 'this' is not the DOM node, but the jQuery object. So, $(this).get(0).setSelectionRange is the same as this.get(0).setSelectionRange, not the same as this.setSelectionRange.
  • $(this)[0] is faster then $(this).get(0)
  • Check out this tutorial for complete solution. webdesignpluscode.blogspot.com/2017/05/…
  • Why would collapse(true) be necessary since you are going to set the end and start selection offsets?
  • @mareoraft: Works on textarea (and input) for me on Chrome, Firefox, IE8, and IE11.
  • I don't seem to be able to get this to work with my script. I have a text area that is empty on page load, then filled by javascript as the application is used. I want the caret to be returned to 0 before each new write (a record of the usage). is it the dynamic data that's causing me problems? if so how could i get around that?
  • What's the significance of the string literal 'character'? Does that specific string need to be used?
  • @Jesse: Dunno how that happened, I usually use 4. Fixed.
  • @UberNeet: Updated based on your suggestion.
  • @Enve: I don't have a copy of IE 5.5 to test with, but that would likely be because jQuery doesn't support IE 5.5.