Skip to content

Instantly share code, notes, and snippets.

@ryanlane
Last active January 11, 2018 21:54
Show Gist options
  • Save ryanlane/eca71ce63f0f4281a9da1189f95396e0 to your computer and use it in GitHub Desktop.
Save ryanlane/eca71ce63f0f4281a9da1189f95396e0 to your computer and use it in GitHub Desktop.
show cursor position of selected text
Try both selecting text and typing.<br>
<textarea onselect="updateInfo(this)" onmousedown="updateInfo(this)" onkeydown="updateInfo(this)"></textarea><br><span id="info"></span>
<script>
function updateInfo(ele) {
var start = ele.selectionStart;
var end = ele.selectionEnd;
if (start!=end) {
document.getElementById("info").innerHTML = "The selection is between "+start+" and "+end+".";
}
else {
document.getElementById("info").innerHTML = "The caret is at "+start+".";
}
}
</script>
Alternative version
function GetSelectedText() {
if (document.getSelection) { // all browsers, except IE before version 9
var sel = document.getSelection();
// sel is a selectionRange object in all browsers except IE before version 9
// the alert method displays the result of the toString method of the passed object
alert(sel);
}
else {
if (document.selection) { // Internet Explorer before version 9
var textRange = document.selection.createRange();
alert(textRange.text);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment