0

I'm trying to add text to textarea in current pointer position, here's the code for PC which works fine:

function getCursor(input){
    var result = { start: 0, end: 0 };
    if (input.setSelectionRange) {
        result.start= input.selectionStart;
        result.end = input.selectionEnd;
    }
    else if (!document.selection) { return 0; }
    else if (document.selection && document.selection.createRange) {
        var range = document.selection.createRange();
        var stored_range = range.duplicate();
        stored_range.moveToElementText(input);
        stored_range.setEndPoint('EndToEnd', range);
        result.start = stored_range.text.length - range.text.length;
        result.end = result.start + range.text.length; //}
    }
    return(result);
} 
function setCursor(txtarea, start, end){
    if(txtarea.createTextRange) {
        var range = txtarea.createTextRange();
        range.move("character", start);
        range.select();
    } else if(txtarea.selectionStart) {
        txtarea.setSelectionRange(start, end);
    }
}
function superChar(){
    start_tag ='"'
    my_text = $('#codeText').get(0);
    my_text.focus();
    var scrtop = my_text.scrollTop;
    var cursorPos = getCursor(my_text);

    if (cursorPos.start==cursorPos.end) {
        var nuCursorPos=cursorPos.start+start_tag.length;
        my_text.value = my_text.value.substring(0,cursorPos.start) + start_tag + my_text.value.substr(cursorPos.start);
        setCursor(my_text, nuCursorPos, nuCursorPos);
    }
    else {
        var txt_pre=my_text.value.substring (0,cursorPos.start);
        var txt_sel=my_text.value.substring(cursorPos.start, cursorPos.end);
        var txt_aft=my_text.value.substring(cursorPos.end);
        my_text.value = txt_pre + start_tag + txt_sel + end_tag + txt_aft;
        var nuCursorPos=String(txt_pre + start_tag + txt_sel + end_tag).length;
        setCursor(my_text, nuCursorPos, nuCursorPos);
    }
    if (scrtop) my_text.scrollTop=scrtop;
}

but on mobile device (android) it always adds symbol to the first letter of text. I have googled it but hadn't found any results.

VoVaVc
  • 771
  • 1
  • 13
  • 31

1 Answers1

0

It seems that it is not straight forward to get the cursor selection on Android. Check out this question for more discussion.

Community
  • 1
  • 1
Paul Beusterien
  • 27,542
  • 6
  • 83
  • 139