user869754
user869754

Reputation: 1

embed some text at the point of the cursor in an html form

Gvien a textarea tag, I can get the coordinates of the cursor using some javascript with onMouseDown when a user clicks there. Now I want to be able to write some text to that point. Is there any way to do that? Thanks for you help, Andynic

Upvotes: 0

Views: 146

Answers (1)

James Hill
James Hill

Reputation: 61812

What you're asking can be difficult. I've found that the code and tutorial here work very well. It will at least get you started.

Here's the code (if you don't want to follow the link):

function insertAtCaret(areaId,text) {
    var txtarea = document.getElementById(areaId);
    var scrollPos = txtarea.scrollTop;
    var strPos = 0;
    var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? 
        "ff" : (document.selection ? "ie" : false ) );
    if (br == "ie") { 
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        strPos = range.text.length;
    }
    else if (br == "ff") strPos = txtarea.selectionStart;

    var front = (txtarea.value).substring(0,strPos);  
    var back = (txtarea.value).substring(strPos,txtarea.value.length); 
    txtarea.value=front+text+back;
    strPos = strPos + text.length;

    if (br == "ie") { 
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        range.moveStart ('character', strPos);
        range.moveEnd ('character', 0);
        range.select();
    }
    else if (br == "ff") {
        txtarea.selectionStart = strPos;
        txtarea.selectionEnd = strPos;
        txtarea.focus();
    }
    txtarea.scrollTop = scrollPos;
}

Upvotes: 1

Related Questions