0

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>
1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231
  • Possible duplicate of [Find out the 'line' (row) number of the cursor in a textarea](https://stackoverflow.com/questions/9185630/find-out-the-line-row-number-of-the-cursor-in-a-textarea) – Venki WAR May 11 '18 at 07:10
  • I think you could listen on "keydown" and "mousemove" event after the textarea has been focused,and stop listening after it's been blured – 亚里士朱德 May 11 '18 at 07:24

0 Answers0