0

Possible Duplicate:
Insert text at cursor in a content editable div

I have this code / jQuery Plugin.

jQuery.fn.extend({
     insertAtCaret: function(myValue) {
        return this.each(function(i) {
            if (document.selection) {
                //For browsers like Internet Explorer
                this.focus();
                sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
            }
            else if (this.selectionStart || this.selectionStart == '0') {
                //For browsers like Firefox and Webkit based
                var startPos = this.selectionStart;
                var endPos = this.selectionEnd;
                var scrollTop = this.scrollTop;
                this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
                this.focus();
                this.selectionStart = startPos + myValue.length;
                this.selectionEnd = startPos + myValue.length;
                this.scrollTop = scrollTop;
            } else {
                this.value += myValue;
                this.focus();
            }
        })
   }

});

This code functions as to insert a non-default character at the caret. Eg, somebody presses the tab key, it inserts \t or they press the E button and it inserts a P instead. The issue I am having is that this code works beautifully in a textarea, but when I try to use it on a contentEditable div, nothing happens. So could I modify this code to work with a contentEditable div instead? Thanks!

EDIT

Demo here: http://jsbin.com/esiced/9/edit

Community
  • 1
  • 1
comu
  • 921
  • 1
  • 11
  • 29
  • Could you replace the `value` property stuff with `innerHTML` ? – alex Oct 23 '11 at 23:22
  • not that I am seeing. Ill post a fiddle and you try. – comu Oct 23 '11 at 23:26
  • http://jsbin.com/esiced/9/edit – comu Oct 23 '11 at 23:37
  • I've answered this before on Stack Overflow. Here's a version that inserts plain text: http://stackoverflow.com/questions/2920150/insert-text-at-cursor-in-a-content-editable-div And here's a version that inserts HTML: http://stackoverflow.com/questions/6690752/insert-html-at-cursor-in-a-contenteditable-div – Tim Down Oct 23 '11 at 23:42

0 Answers0