Set keyboard caret position in html textbox
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 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>
jQuery: Add letter from virtual keyboard to the caret position in the input box
The following code allows you to select multiple characters and replace all of them by clicking the button. Additionally, it will place the cursor directly after the point where the special character is inserted.
Note: I replaced $this = $(this)
in favor of just using $(this).html();
in the textAreaStr
variable assignment only because it shortens the code, not because your method was incorrect.
$('#e_specchar').click(function(){
var selStart = $("#input")[0].selectionStart;
var selEnd = $("#input")[0].selectionEnd;
var character = $(this).html();
var textAreaStr = $('#input').val();
var value = textAreaStr.substring(0, selStart) + character + textAreaStr.substring(selEnd);
$("#input").val(value).focus();
$("#input")[0].selectionStart = selStart+1, $("#input")[0].selectionEnd = selStart+1;
});
DEMO
How to restore caret position in Javascript?
You can use Range
and Selection
objects as described in this answer:
function restore() {
var el = document.getElementById("editable");
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el, 0);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
p {
text-align:left;
padding:10px;
font-size: 20px;
font-family: "Open Sans";
border:1px black solid;
}
button{
font-size: 25px;
}
<p id="editable" contenteditable="true"></p>
<button onclick="restore()">Restore</button>
Trying to set the cursor position inside a textbox after updating the model object
try this:
updateText(str:String){
this.myString+=str;
setTimeout(()=>{
this.myTextBox.focus();
this.myTextBox.setSelectionRange(2,2);
},0);
}
How to set cursor position at the end of input text in Google Chrome
It seems like the focus event is fired before the cursor is placed when you focus an input, a hacky workaround would be to use a setTimeout like so:
$('#Search').focus(function() {
setTimeout((function(el) {
var strLength = el.value.length;
return function() {
if(el.setSelectionRange !== undefined) {
el.setSelectionRange(strLength, strLength);
} else {
$(el).val(el.value);
}
}}(this)), 0);
});
Try this fiddle: http://jsfiddle.net/esnvh/26/
Edited to 0ms timeout, as @SparK pointed out this is enough to push to end of execution queue.
Set caret to nearest possible position based on an x and y coordinate
I found the solution:
function moveCaret(x, y) {
let sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(document.caretRangeFromPoint(x, y));
}
The function moves the caret to the nearest possible position. Tested on chromium browser like Opera, Edge or Chrome.
I found a cross browser solution (after knowing the name of caretRangeFromPoint
function) here on stack overflow. If you're looking for a cross browser solution please take a look here: https://stackoverflow.com/a/11191372/1635166
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>
Related Topics
Pad a Number With Leading Zeros in JavaScript
How to Get Element by Class in JavaScript
How to Simulate a Click With JavaScript
I'Ve Heard Global Variables Are Bad, What Alternative Solution Should I Use
Typeerror: $(...).Modal Is Not a Function with Bootstrap Modal
Count Animation from Number a to B
What Is the Best Method to Reduce the Size of My JavaScript and CSS Files
How to Programmatically Add Js and CSS Resources to <H:Head>
Ruby's ||= (Or Equals) in JavaScript
How to Use Jquery with Node.Js
How to Post Urlencoded Form Data With $Http Without Jquery
"Syntaxerror: Unexpected Token ≪ in Json At Position 0"
Angularjs Routing Without the Hash '#'
Event.Preventdefault() Function Not Working in Ie
Jspdf Can't Get Any Styling to Work
How to Make Changeable Themes Using CSS and JavaScript
Get the Size of a CSS Background Image Using JavaScript
Example of How to Load Static CSS Files from Node_Modules Using Webpack