DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Insert Text In Current Position In Textarea

  • submit to reddit
        // description of your code here

//modified version of
//myField accepts an object reference, myValue accepts the text string to add
function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {

        //in effect we are creating a text range with zero
        //length at the cursor location and replacing it
        //with myValue
        sel = document.selection.createRange();
        sel.text = myValue;

    //Mozilla/Firefox/Netscape 7+ support
    } else if (myField.selectionStart || myField.selectionStart == '0') {

        //Here we get the start and end points of the
        //selection. Then we create substrings up to the
        //start of the selection and from the end point
        //of the selection to the end of the field value.
        //Then we concatenate the first substring, myValue,
        //and the second substring to get the new value.
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
        myField.setSelectionRange(endPos+myValue.length, endPos+myValue.length);
    } else {
        myField.value += myValue;


Snippets Manager replied on Mon, 2009/11/02 - 12:37am

the above code worked well in both IE 8 and firefox 3.5. When the text inside the textarea is long and the current cursor is some where bottom (i.e. the scroll bar isn't in its top position) the insertion works fine but the scroll bar position is lost (i.e the scroll bar is set to its top position). To avoid this, the current scroll bar position can be saved before changing the textarea content, and after changing the textarea content the scroll bar position can be restore back. //add this to the start of function textAreaScrollPosition = myField.scrollTop; //add this to end of the function myField.scrollTop = textAreaScrollPosition; happy coding!!