8

On a function call from an image, I am trying to insert the alt tag value from the image into the textarea at the position where the caret currently is.

This is the code that I currently have which inserts the alt tag value to the end of the text area.

    $("#emoticons").children().children().click(function () {
        var ch = $(this).attr("alt");
        $("#txtPost").append(ch);

    }); 

The 2 things I have been having a problem with is determining the position of the caret, and creating a new string with the value of the textarea before the carets positon + the code I'm inserting + the value of the textarea after the carets position.

Omer Bokhari
  • 57,458
  • 12
  • 44
  • 58
Stefan H
  • 6,635
  • 4
  • 24
  • 35
  • possible duplicate of [Inserting a text where cursor is using Javascript/jquery](http://stackoverflow.com/questions/1064089/inserting-a-text-where-cursor-is-using-javascript-jquery) – user Jul 26 '15 at 05:46
  • If you're looking for a simple module with undo support, try [insert-text-textarea](https://github.com/bfred-it/insert-text-textarea). If you need IE8+ support, try the [insert-text-at-cursor](https://www.npmjs.com/package/insert-text-at-cursor) package. – fregante Mar 29 '19 at 01:52

1 Answers1

19

i've currently got this extension in place:

$.fn.insertAtCaret = function(text) {
    return this.each(function() {
        if (document.selection && this.tagName == 'TEXTAREA') {
            //IE textarea support
            this.focus();
            sel = document.selection.createRange();
            sel.text = text;
            this.focus();
        } else if (this.selectionStart || this.selectionStart == '0') {
            //MOZILLA/NETSCAPE support
            startPos = this.selectionStart;
            endPos = this.selectionEnd;
            scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos) + text + this.value.substring(endPos, this.value.length);
            this.focus();
            this.selectionStart = startPos + text.length;
            this.selectionEnd = startPos + text.length;
            this.scrollTop = scrollTop;
        } else {
            // IE input[type=text] and other browsers
            this.value += text;
            this.focus();
            this.value = this.value;    // forces cursor to end
        }
    });
};

and you can use it like so:

$("#txtPost").insertAtCaret(ch);
Omer Bokhari
  • 57,458
  • 12
  • 44
  • 58