Javascript textarea cursor position change

How do you get the cursor position in a textarea?

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.

var firstNewline = $('#myTextarea').val().indexOf('\n'); var lastNewline = $('#myTextarea').val().lastIndexOf('\n'); var cursorPosition = . ; if (cursorPosition < firstNewline) // I am on first line. else if (cursorPosition >lastNewline) // I am on last line. 
  • Is it possible to grab the cursor position within the textarea?
  • Do you have a better suggestion for finding out if I am on the first or last line of a textarea?

jQuery solutions preferred unless JavaScript is as simple or simpler.

This will throw an error, as the indexOf and lastIndexOf` functions are not methods of the val` function. You should use this (although you shouldn’t use that code at all): var firstNewline = String($(«#myTextarea»).val()).indexOf(‘\n’);

The cursor is your mouse pointer, the caret is the indicator where the text controller is present.

@John Thanks for the description. To go further, conceptually a caret represents a location in text while a cursor represents a location in anything. Regarding graphical interfaces, they have distinct purposes and, often, different physical renderings.

Источник

Set text-cursor position in a textarea

Everything is OK except one thing which is the position of the text-cursor. When I click on the boldText button, it sets the cursor position at the end of the Textarea!! Actually, I want to be able to set the cursor position at a certain index. I want something like this:

6 Answers 6

After refocusing the textarea with txtarea.focus() , add this line:

txtarea.selectionEnd= end + 7; 

That will set the cursor seven positions ahead of where it was previously, which will take [b][/b] into account.

document.getElementById('bold').addEventListener('click', boldText); function boldText() < var txtarea = document.getElementById("editor_area"); var start = txtarea.selectionStart; var end = txtarea.selectionEnd; var sel = txtarea.value.substring(start, end); var finText = txtarea.value.substring(0, start) + '[b]' + sel + '[/b]' + txtarea.value.substring(end); txtarea.value = finText; txtarea.focus(); txtarea.selectionEnd= end + 7; >

if you are using jquery you can do it like this.

$('textarea').prop('selectionEnd', 13); 

you can use these 2 functions below written by Jamie Munro ( setSelectionRange() & setCaretToPos() ):

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)

for example, if you want to set the caret at the end of your textarea you can have this: setCaretToPos(document.getElementById(‘textarea’), -1);

Читайте также:  Untitled Document

Realizing this is an older question, this is offered only as something to think about as an option now because it may likely be more efficient than extracting and assembling pieces of the textarea value string, and it sets the cursor automatically based on the fourth argument of setRangeText and autofocuses also. It works in Firefox 66.0.02 and I haven’t tested it elsewhere. The cursor is placed after the ‘[/b]’.

 t = document.getElementById("editor_area"); b = t.selectionStart, e = t.selectionEnd + 3; // length of '[b]' t.setSelectionRange( b, b ); t.setRangeText( '[b]' ); t.setSelectionRange( e, e ); t.setRangeText( '[/b]', e, e, 'end' ); 
 var cursorPos = $('#textarea').prop('selectionStart'); $('#textarea').prop('selectionEnd',cursorPos-2); 

This is a little OT, but if anyone is interested:

  • Brief: Set cursor inside input element throug row and column
  • Dependency: setSelectionRange() from @ashkan nasirzadeh
  • Example call: setTextCursor(textarea,textarea.val, 0, 1);
// @brief: set cursor inside _input_ at position (column,row) // @input: input DOM element. E.g. a textarea // @content: textual content inside the DOM element // @param row: starts a 0 // @param column: starts at 0 function setTextCursor(input, content, row, column) < // search row times: var pos = 0; var prevPos = 0; for( var i = 0; (i// if we can't go as much down as we want, // go as far as worked if(-1 == pos) < pos = prevPos; >if(0 != row) ++pos; // one for the linebreak // prevent cursor from going beyond the current line var lineEndPos = content.indexOf("\n", pos+1); if((-1 != lineEndPos) && (column > lineEndPos-pos)) < // go *only* to the end of the current line pos = lineEndPos; >else < // act as usual pos += column >setSelectionRange(input, pos,pos); > 

Источник

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 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.

11 Answers 11

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

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.

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

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) else if (document.selection) 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(); >> 

+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.

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

// ** 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; >> > > 

Источник

How can you move the cursor to the last position of a textarea in Javascript?

I have a textarea and a button on a form. The textarea may already have some text in it. I would like the cursor to move to the last position in the text area when the button is clicked. Is this possible?

7 Answers 7

xgMz’s answer was best for me. You don’t need to worry about the browser:

var html = $("#MyTextArea").val(); $("#MyTextArea").focus().val("").val(html); 

And here’s a quick jQuery extension I wrote to do this for me next time:

By “the last position”, do you mean the end of the text?

Changing the ‘.value’ of a form field will move the cursor to the end in every browser except IE. With IE you have to get your hands dirty and deliberately manipulate the selection, using non-standard interfaces:

Or do you mean put the cursor back to the place it was previously, the last time the textarea was focused?

In every browser except IE, this will already happen just by calling ‘element.focus()’; the browser remembers the last cursor/selection position per input and puts it back on focus.

This would be quite tricky to reproduce in IE. You would have to poll all the time to check where the cursor/selection was, and remember that position if it was in an input element, then fetch the position for a given element when the button was pressed and restore it. This involves some really quite tedious manipulation of ‘document.selection.createRange()’.

I’m not aware of anything in jQuery that would help you do this, but there might be a plugin somewhere perhaps?

Источник

Оцените статью