I have a text area that users can enter text in. When they select text I'd like to get the row and column of the selected text (or cursor) if they do not select any text.
The example below is using the on focus event. It should use a cursor change or selection change event.
document.getElementById('textarea').onselectionchange = onFocusHandler;
document.getElementById('textarea').onselect = onFocusHandler;
document.getElementById('textarea').onfocus = onFocusHandler;
document.getElementById('textarea').onmouseup = onFocusHandler;
document.getElementById('textarea').onselectionstart = onFocusHandler;
function onFocusHandler(event){
var textarea = document.getElementById('textarea');
var value = textarea.value;
var anchorPosition = 0;
var activePosition = 0;
var userSelection;
var range;
console.log(event.type);
if (window.getSelection) {
//console.log("1");
userSelection = window.getSelection();
//console.log(userSelection);
//range = userSelection.getRangeAt(0);
//console.log(range);
}
else if (document.selection) {
userSelection = document.selection.createRange();
}
console.log("Cursor:" + userSelection.anchorOffset);
return;
if (userSelection.getRangeAt) {
//range = userSelection.getRangeAt(0);
}
else {
range = document.createRange();
range.setStart(userSelection.anchorNode, userSelection.anchorOffset);
range.setEnd(userSelection.focusNode, userSelection.focusOffset);
}
//console.log(range);
textarea.focus();
if (textarea.setSelectionRange) {
textarea.setSelectionRange(anchorPosition, activePosition);
}
else {
var range = textarea.createTextRange();
range.collapse(true);
range.moveEnd('character', activePosition);
range.moveStart('character', anchorPosition);
range.select();
}
};
<textarea id="textarea" style="width:100%;height:100px">Hello world.
It's a nice day.
Go outside and get some sun.
</textarea>
<span id="row">Row</span>