Last active
January 11, 2018 21:54
-
-
Save ryanlane/eca71ce63f0f4281a9da1189f95396e0 to your computer and use it in GitHub Desktop.
show cursor position of selected text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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