How to shift cursor position in a text using javascript [duplicate] - javascript

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

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

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

I found an easy way to fix this issue, tested in IE and Chrome:
function setCaret(elemId, caret)
{
var elem = document.getElementById(elemId);
elem.setSelectionRange(caret, caret);
}
Pass text box id and caret position to this function.

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

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

function SetCaretEnd(tID) {
tID += "";
if (!tID.startsWith("#")) { tID = "#" + tID; }
$(tID).focus();
var t = $(tID).val();
if (t.length == 0) { return; }
$(tID).val("");
$(tID).val(t);
$(tID).scrollTop($(tID)[0].scrollHeight); }

I would fix the conditions like below:
function setCaretPosition(elemId, caretPos)
{
var elem = document.getElementById(elemId);
if (elem)
{
if (typeof elem.createTextRange != 'undefined')
{
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else
{
if (typeof elem.selectionStart != 'undefined')
elem.selectionStart = caretPos;
elem.focus();
}
}
}

<!DOCTYPE html>
<html>
<head>
<title>set caret position</title>
<script type="application/javascript">
//<![CDATA[
window.onload = function ()
{
setCaret(document.getElementById('input1'), 13, 13)
}
function setCaret(el, st, end)
{
if (el.setSelectionRange)
{
el.focus();
el.setSelectionRange(st, end);
}
else
{
if (el.createTextRange)
{
range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', st);
range.select();
}
}
}
//]]>
</script>
</head>
<body>
<textarea id="input1" name="input1" rows="10" cols="30">Happy kittens dancing</textarea>
<p> </p>
</body>
</html>

HTMLInputElement.setSelectionRange( selectionStart, selectionEnd );
// References
var e = document.getElementById( "helloworldinput" );
// Move caret to beginning on focus
e.addEventListener( "focus", function( event )
{
// References
var e = event.target;
// Action
e.setSelectionRange( 0, 0 ); // Doesn’t work for focus event
window.setTimeout( function()
{
e.setSelectionRange( 0, 0 ); // Works
//e.setSelectionRange( 1, 1 ); // Move caret to second position
//e.setSelectionRange( 1, 2 ); // Select second character
}, 0 );
}, false );
Browser compatibility (only for types: text, search, url, tel and password):
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange#Specifications

Related

Logic for returning caret position for changed input

I'll be thankful for feedback on how i should build a logic of returning caret position for modified input.
Case: we have an input, processed by JS to be formatted like x999y999z9999, where x,y,z - are dividers we define on case by case basis. We process and modify it as intended, but i seem to become lost in logic for returning user's caret position in context of those x,y&z of variable length. I'm even kinda inclined to build a whole complex of if\else in response to those length fluctuations, but there probably is a simpler solution, which i'm missing.
Thanks in advance!
Code example: https://jsfiddle.net/zktva4kc/
function doGetCaretPosition (field) {
if (!!field){
var CaretPos = 0;
// IE Support
if (document.selection) {
field.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -field.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (field.selectionStart || field.selectionStart == '0')
CaretPos = field.selectionStart;
return (CaretPos);
}else{
console.log("No such field exist here for function initiation.");
}
}
function setCaretPosition(field, pos)
{
if (!!field){
if(field.setSelectionRange)
{
field.focus();
field.setSelectionRange(pos,pos);
}
else if (field.createTextRange) {
var range = field.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}else{
console.log("No such field exist here for function initiation.");
}
}
function formatItDown(field, format) {
if (!!field){
field.oninput = function () {
var position=doGetCaretPosition(field);
var sInput=this.value;
var input = this.value;
input = input.replace(/[^\d]/gi, "");
var first = input.substr(0, 3);
var second = input.substr(3, 3);
var third = input.substr(6, 4);
if (input.length > 3) {
first = format[0] + first + format[1];
}
if (input.length > 6) {
second = second + format[2];
}
formatted = first + second + third;
//x012y456z8901
/* this here is the problem area when we use some complex formats
if ((formatted[3]!=sInput[3])&&(position>3)&&(position<6)){
position=position+1;
}else if ((formatted[7]!=sInput[7])&&(position>7)){
position=position+1;
}*/
this.value = formatted;
setCaretPosition(field, position);
}
}else{
console.log("No such field exist here for function initiation.");
}
}
formatItDown(document.getElementById('exampleInput'), ["--","==","__"]);
<input id='exampleInput'>
Why not quickly google for something well coded and bug free ?
Here is a good plugin I used once
https://github.com/acdvorak/jquery.caret

Bold a specific text inside a contenteditable div

I have this in my contenteditable div. Whenever I type #something, then type space, I would like to bold that word instantly in that div.
E.g.
This is my message. #lol. I would like to bold the hashtag.
Below is the code I have
<div id="message" name="message" contenteditable="true"></div>
$('#message').keyup(function(e){
var len = $(this).val().length;
if ($(this).val().substring(length - 1, 1) == '#') {
}
//detect space
if(e.keyCode == 32){
}
});
I am using jquery. How do i go about doing so?
Using contenteditable = "true" may be tricky, but this is a possible solution:
The text is bold when a word is preceded by #
Example: hello #world, this is a #sample
HTML:
<div id="divEditable" contenteditable="true"></div>
JavaScript: jsbin.com/zisote
We are going to split the code, but actually it is wrapped in an IIFE
/*** Cached private variables ***/
var _break = /<br\s?\/?>$/g,
_rxword = /(#[\w]+)$/gm,
_rxboldDown = /<\/b>$/gm,
_rxboldUp = /<\/b>(?!<br\s?\/?>)([\w]+)(?:<br\s?\/?>)?$/,
_rxline = /(<br\s?\/?>)+(?!<b>)(<\/b>$)+/g;
/*** Handles the event when a key is pressed ***/
$(document).on("keydown.editable", '.divEditable', function (e) {
//fixes firefox NodeContent which ends with <br>
var html = this.innerHTML.replace(_break, ""),
key = (e.which || e.keyCode),
dom = $(this);
//space key was pressed
if (key == 32 || key == 13) {
//finds the # followed by a word
if (_rxword.test(dom.text()))
dom.data("_newText", html.replace(_rxword, "<b>$1</b> "));
//finds the end of bold text
if (_rxboldDown.test(html))
dom.data("_newText", html + " ");
}
//prevents the bold NodeContent to be cached
dom.attr("contenteditable", false).attr("contenteditable", true);
});
/*** Handles the event when the key is released ***/
$(document).on("keyup.editable", '.divEditable', function (e) {
var dom = $(this),
newText = dom.data("_newText"),
innerHtml = this.innerHTML,
html;
//resets the NodeContent
if (!dom.text().length || innerHtml == '<br>') {
dom.empty();
return false;
}
//fixes firefox issue when text must follow with bold
if (!newText && _rxboldUp.test(innerHtml))
newText = innerHtml.replace(_rxboldUp, "$1</b>");
//fixes firefox issue when space key is rendered as <br>
if (!newText && _rxline.test(innerHtml)) html = innerHtml;
else if (newText && _rxline.test(newText)) html = newText;
if (html) newText = html.replace(_rxline, "$2$1");
if (newText && newText.length) {
dom.html(newText).removeData("_newText");
placeCaretAtEnd(this);
}
});
/*** Sets the caret position at end of NodeContent ***/
function placeCaretAtEnd (dom) {
var range, sel;
dom.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
range = document.createRange();
range.selectNodeContents(dom);
range.collapse(false);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
//this handles the text selection in IE
range = document.body.createTextRange();
range.moveToElementText(dom);
range.collapse(false);
range.select();
}
}
You can play with live code here: jsbin.com/zisote
Here is a sample. An editable div is not a good idea though. Try to change this. A textarea maybe is better...
http://jsfiddle.net/blackjim/h9dck/5/
function makeBold(match, p1, p2, p3, offset, string) {
return p1+'<b>' + p2 + '</b>'+p3;
};
$('#message').keyup(function (e) {
var $this = $(this);
//detect space
if (e.keyCode == 32) {
var innerHtml = $this.html();
innerHtml = innerHtml.replace(/(.*[\s|($nbsp;)])(#\w+)(.*)/g, makeBold);
if(innerHtml !== $this.html()){
$this.html(innerHtml)
.focus();
}
}
});

Set caret to end of textbox on focus

The Question:
When a certain textbox receives focus, set the caret to the end of the textbox. The solution needs to work with IE7, Opera, Chrome and Firefox.
To make things a bit easier, this behavior is only needed when the current value of the textbox is a fixed value. (Say 'INIT')
Incomplete Solutions:
One would expect this to be pretty simple but I couldn't find an answer on SO that works on all browsers. The following answers do NOT work:
$("#test").focus(function() {
// This works for Opera only
// Also tested with $(this).val($(this).val());
if (this.value == "INIT") {
this.value = "";
this.value = "INIT";
}
});
$("#test").focus(function() {
// This works for IE and for Opera
if (this.value == "INIT") {
setCaretPosition(this, 4);
}
});
I got the setCaretPosition function from SO questions and saw it on different blogs aswell:
function setCaretPosition(ctrl, pos) {
if (ctrl.setSelectionRange) {
//ctrl.focus(); // can't focus since we call this from focus()
// IE only
ctrl.setSelectionRange(pos, pos);
}
else if (ctrl.createTextRange) {
// Chrome, FF and Opera
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos); // Also tested with this
range.moveStart('character', pos); // and this line in comment
range.select();
}
}
Fiddle
I've setup a jsFiddle.
Try this:
$("input").on("focus", function() {
if (this.value === "INIT") {
var input = this;
setTimeout(function() {
if (input.createTextRange) {
var r = input.createTextRange();
r.collapse(true);
r.moveEnd("character", input.value.length);
r.moveStart("character", input.value.length);
r.select();
}
else {
input.selectionStart = input.selectionEnd = input.value.length;
}
}, 13);
}
});
http://jsfiddle.net/azBxU/4/
This should work:
$("#test").focus(function() {
var $this = $(this);
var value = $this.val();
if (value === "INIT") {
setTimeout(function() {
$this.val(value);
}, 0);
}
});
I found a jQuery plugin that's been working for me for a long time. Can't remember where though.
(function($)
{
jQuery.fn.putCursorAtEnd = function() {
return this.each(function() {
$(this).focus()
// If this function exists...
if (this.setSelectionRange) {
// ... then use it
// (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
} else {
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
})(jQuery);

Text selection in div(contenteditable) when double click

I have div with some text and contenteditable="true". When I single click on this div - works some my scripts, it is not very important. And when I double click on this div - need to edit text in div. Edit text need to be only after double click, not after single. And very imortant, when I double click on div - caret need stay under mouse cursor. No need selection text. I found some script for single/double. But have problem. When I double click on div - text are selection. Selection no need. Need editor caret where I clicked. I do not understand how.
http://jsfiddle.net/X6auM/
Every current major browser provides an API to create a range from a mouse event, although there are four different code branches needed.
Here is some background:
https://stackoverflow.com/a/10659990/96100
https://stackoverflow.com/a/12705894/96100
Creating a collapsed range from a pixel position in FF/Webkit
Here's a demo: http://jsfiddle.net/timdown/krtTD/10/
And here's some code:
function getMouseEventCaretRange(evt) {
var range, x = evt.clientX, y = evt.clientY;
// Try the simple IE way first
if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToPoint(x, y);
}
else if (typeof document.createRange != "undefined") {
// Try Mozilla's rangeOffset and rangeParent properties,
// which are exactly what we want
if (typeof evt.rangeParent != "undefined") {
range = document.createRange();
range.setStart(evt.rangeParent, evt.rangeOffset);
range.collapse(true);
}
// Try the standards-based way next
else if (document.caretPositionFromPoint) {
var pos = document.caretPositionFromPoint(x, y);
range = document.createRange();
range.setStart(pos.offsetNode, pos.offset);
range.collapse(true);
}
// Next, the WebKit way
else if (document.caretRangeFromPoint) {
range = document.caretRangeFromPoint(x, y);
}
}
return range;
}
function selectRange(range) {
if (range) {
if (typeof range.select != "undefined") {
range.select();
} else if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
}
document.getElementById("editor").ondblclick = function(evt) {
evt = evt || window.event;
this.contentEditable = true;
this.focus();
var caretRange = getMouseEventCaretRange(evt);
// Set a timer to allow the selection to happen and the dust settle first
window.setTimeout(function() {
selectRange(caretRange);
}, 10);
return false;
};
$('p').dblclick(function(event) {
$this = $(this);
$this.attr('contenteditable', "true");
$this.blur();
$this.focus();
});
http://jsfiddle.net/krtTD/90/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<!-- <link rel="stylesheet" href="../tailwind.css" /> -->
</head>
<body>
<div id="editor" style="user-select:none;" contenteditable="false">Some editableasa text. Double click to eadsit</div>
<script>
function getMouseEventCaretRange(evt) {
var range, x = evt.clientX, y = evt.clientY;
// Try the simple IE way first
if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToPoint(x, y);
}
else if (typeof document.createRange != "undefined") {
// Try Mozilla's rangeOffset and rangeParent properties, which are exactly what we want
if (typeof evt.rangeParent != "undefined") {
range = document.createRange();
range.setStart(evt.rangeParent, evt.rangeOffset);
range.collapse(true);
}
// Try the standards-based way next
else if (document.caretPositionFromPoint) {
var pos = document.caretPositionFromPoint(x, y);
range = document.createRange();
range.setStart(pos.offsetNode, pos.offset);
range.collapse(true);
}
// Next, the WebKit way
else if (document.caretRangeFromPoint) {
range = document.caretRangeFromPoint(x, y);
}
}
return range;
}
function selectRange(range) {
if (range) {
if (typeof range.select != "undefined") {
range.select();
} else if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
}
document.getElementById("editor").ondblclick = function (evt) {
evt = evt || window.event;
this.contentEditable = true;
this.focus();
var caretRange = getMouseEventCaretRange(evt);
selectRange(caretRange);
this.style = ""
};
</script>
</body>
</html>
An improvement of accepted answer that does not create the temp flash it uses css user-select property to it's advantage

How to get range of selected text of textarea in JavaScript

I am trying to retrieve/find the start point and end point of selection in textarea.
Here is my code which work fine in Mozilla and chrome, but it is not working in Internet Explorer 9:
<script type="txt/javascript">
function update(o) {
var t = o.value, s = getSelectionStart(o), e = getSelectionEnd(o);
alert("start: " + s + " End: " + e);
}
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
rse = r.text.length;
r.moveEnd('character', o.value.length)
if (r.text == '')
return o.value.length
return o.value.lastIndexOf(r.text)
}
else
return o.selectionStart
}
function getSelectionEnd(o) {
if (o.createTextRange) {
var r = document.selection.createRang;
e().duplicate()
r.moveStart('character', -o.value.length)
return r.text.length
}
else
return o.selectionEnd
}
</script>
<textarea id ="text" rows=10 cols="50" onselect="update(this);"></textarea>
When I test this code in Mozilla and Chrome, it gives me correct answer, but when I run this code in Internet Explorer 9, it shows -1 for start and any value for end.
I want to just find out the start and end point/index of the selected text of the textarea. Actually, the above code works fine for a textbox in all browsers, but not with textarea.
How can I fix it?
Use the code below or check this fiddle
function getTextSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
alert("start :" + start + " End :" + end);
}
While the original answer may have helped the OP in 2012, things have changed, and this has now become simpler, at least in modern browsers.
You can use the JavaScript selectionStart and selectionEnd attributes of the textarea.
Basic Usage
These are both standard attributes that will work in today's major browsers (Chrome, Safari, Firefox, Opera, Edge, and IE).
For example:
console.log(
document.getElementById("text").selectionStart,
document.getElementById("text").selectionEnd
)
will show both the start and end point of the selection in the textarea with the ID text.
Boundary Cases
If there is no item selected in the textarea, then both the start and end attributes will return the last position of the caret. If the textarea has not received focus yet, the attributes will both return a value of 0.
Changing the Selection
By setting these attributes to new values, you will adjust the active text selection. Thus, you can also use this to select text in a textarea.
Checking if a selection is in place
You can check if there is currently a selection by checking if the values are both different, i.e. if
document.getElementById("text").selectionStart != document.getElementById("text").selectionEnd
is true, then there is a text selection.
Demo
const textarea = document.getElementById("text");
const selStart = document.getElementById("selStart");
const selEnd = document.getElementById("selEnd");
// should maybe also look at other events, e.g. "keydown", "select", etc
textarea.addEventListener("mousemove", () => {
selStart.innerText = textarea.selectionStart;
selEnd.innerText = textarea.selectionEnd;
});
<textarea id="text">Some text here</textarea>
<p>Selection Start: <span id="selStart">0</span></p>
<p>Selection End: <span id="selEnd">0</span></p>
References
Live Demo (JSFiddle)
Documentation at MDN
Documentation at MSDN

Categories