Jquery Set Cursor Position in Text Area

jQuery Set Cursor Position in Text Area

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 Textarea Cursor to End of Text

Something simple you can do is reset the text area's value:

$(function() {
var data = $('textarea').val();
var emoticon = ':)';
$('textarea').focus().val('').val(data + emoticon);
});

Set text-cursor position in a textarea

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.

Example

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;}
#editor_area {  width: 100%;  height: 10em;}
<button id="bold">B</button><textarea id="editor_area"></textarea>

How to set cursor position in a textarea where I last inserted the text?

Simply use this selectionEnd and sum with txt_to_add length

$(document).ready(function() {
// Get current cursor position $("#btngetcurpos").click(function() { var cursor_pos = $("#my_textarea").prop('selectionStart'); alert(cursor_pos); $("#my_textarea").focus(); });
// Insert text at current cursor position $("#btnsettxt").click(function() { var cursor_pos = $("#my_textarea").prop('selectionStart'); var textarea_txt = $("#my_textarea").val(); var txt_to_add = "test"; $("#my_textarea").val(textarea_txt.substring(0, cursor_pos) + txt_to_add + textarea_txt.substring(cursor_pos)); $("#my_textarea").focus(); $('#my_textarea').prop('selectionEnd', cursor_pos + txt_to_add.length);
});});
#my_textarea {  border: 1px solid red;  width: 300px;  height: 100px;  padding: 5px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<textarea id="my_textarea" autofocus>This is a textarea.</textarea>
<br /><br />
<input type="button" id="btngetcurpos" value="Get Cursor Position" />
<input type="button" id="btnsettxt" value="Insert Text" />

Place cursor at the 2nd line of a textarea with jQuery/JavaScript

Why would there be any magic? This is what setSelectionRange is for. Just remember that you won't see the cursor unless you're focussed on the textarea, and if you do so by clicking on it, you're also automatically placing the cursor wherever you clicked:

let text = document.querySelector(`textarea`);
let pos = text.textContent.indexOf(`\n`);
text.setSelectionRange(pos+1, pos+1);
text.focus();
<textarea cols="20" rows="4">
Dear sir,

Best regards,
John Smith
</textarea>

Set cursor position at the beginning of the line

There are two ways to set the cursor to a particular position in an input:

  1. setSelectionRange(startPosition, endPosition);: This selects the text between the two provided positions. If the start and end are the same, then the cursor is just placed before the character at that position. So, to place the cursor at beginning you would do a setSelectionRange(0, 0);.
  2. setCursorPosition(position);: This actually moves the cursor to the position provided. So, to place the cursor at beginning you would do a setCursorPosition(0);.

After having tried your code, it seems that on focus (especially via click), the cursor is placed at the point of click and the setSelectionRange and/or setCursorPosition gets overridden.

One possible workaround would be to wrap this in a timer to induce a faux-delay. Something like this:

Demo: http://jsfiddle.net/abhitalks/vU5yf/5/

Relevant Code:

jQuery.fn.cleardefault = function() {
return this.focus(function(e) {
if( this.value == this.defaultValue ) {
this.value = ".company.com";
var t = this;
window.setTimeout(function() {
t.setSelectionRange(0, 0);
// t.setCursorPosition(0);
}, 0);
}
}).blur(function(e) {
if( !this.value.length ) {
this.value = this.defaultValue;
}
});
};


jQuery(".clear").cleardefault();

You may try to increase the timeout by a little amount to tweak it, if required. But, don't make it too high otherwise there's a possibility the user will be able to input another character before the timer fires.

jQuery Set Cursor to Beginning of Input Field on Focus

This will bind the focus AND click events of the input field to the function. Hope this helps!

$('#email').on('focus click', function() {  $(this)[0].setSelectionRange(0, 0);})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><input type="text" placeholder="Enter your name" autofocus><input type="text" id="email" value="@website.com">

Set cursor to specific position on specific line in a textarea

I've updated your fiddle see: http://jsfiddle.net/eghpf/2/

I've added var currentPosition which is used in this method

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

Which comes from this jQuery Set Cursor Position in Text Area

What happens (is the reason why the cursor is always on the last position); is when you call $('#systemNotesbuilder').val(arrayOfLines.join("\n")); the entire value gets overwritten with a new value placing the cursor after that new value. The call to set the cursor is (and should) be after that call.

How to set cursor position in particular input text in html and javascript

You can do something like this:

$('[name=textbox2]').focus(function(){
if($('[name=textbox1]').val() == ''){
$('[name=textbox1]').focus();
}
});

WORKING FIDDLE



Related Topics



Leave a reply



Submit